Stream Processing - Apache Storm
Introduction
Hadoop
Strength:
- Batch processing
- simple programming model
- Massively scalable
- 1000’s node cluster w/ commodity hardware
- High throughout
- Move computation to the data nodes
- Highly available
- Built-in failover
- Batch processing
Weakness:
- High Latency
- Minutes or even hours
- Poor support for Interactive Analysis
- Inability to Rapidly Respond to Special/ Unexpected Events
- High Latency
Stream Processing
- Stream Processing is an infrastructure for continuous (non-stopped, never-ending) data processing
- Computational model can be as general as MapReduce but with the ability to produce results under low-latency constraint
- Input Data collected continuously is naturally processed continuously
Also known as Event Processing or Complex Event Processing (CEP)

Architectural Pattern
Architectural Patterns to support BOTH Real-Time and Batched Big Data Processing
A Standalone Event Stream Processing System: The Two-Pronged Approach
Fast Real-Time path with Batch Backup reduces complexity and improves performance

Event Stream Processing as part of the Lambda Architecture
- Event Stream Processing as part of the Kappa Architecture (from LinkedIn)
Apache Storm
Motivation
Traditional Workflow under the Queues-Workers Model for Event Processing:
- Workers schemify tweets and append to Hadoop
- Workers update statistics on URLs by incrementing counters in Cassandra

Problems:
- It is difficult to scale up as it involves Queue-partitioning and deployment of additional Workers (processes/nodes), it is difficult to redistribute the data during the processing
- Operational overhead due to Worker failures and Queue-Backups
- No guarantees on whether incoming Data is being processed
Solution from Apache Storm:
- Focus on the support of Real-Time Streaming jobs
- To simplify dealing with queues (for tasks) and many workers (for load balancing/parallelization)
- Higher level abstraction than message passing
- Support Guaranteed data processing (at least once)
- Horizontal scalability
- Fault-tolerance
- Complementary to Hadoop:
- The “Hadoop” of real time streaming jobs
Key Concepts:
Stream:
- An Unbounded sequence of Tuples
- Core Abstraction in Storm
- Defined with a Schema that names the fields in the Tuple
- Value must be serializable n Every Stream has an ID
Topologies:
- A Directed Acyclic Graph (DAG) where each node is either a Data source (Spout) or a Processing node (Bolt)
- An Edge indicates which Bolt subscribes to which Stream

Spout: Source of data stream (tuples), e.g.
- Read from the Twitter streaming API (tuples = tweets)
- Read from a http server log (tuples = http requests)
- Read from a Kafka queue (tuples = events)

Bolt: Processes 1+ input streams and produces 1+ new streams, complex operations may need more than 1 Bolt
- e.g. Calculate, Functions, Filters, Aggregation, Joins, talk to database

- e.g. Calculate, Functions, Filters, Aggregation, Joins, talk to database
Each Spout or Bolt is executed as one or more Tasks (instances) across the cluster
Worker(JVM)Process:
- Executes subset of a Topology
- May run 1 or more threads (Executors) for one or more components
- One Thread per Executor
Tasks:
- The actual data processing instance executing by the thread
- It is possible for multiple tasks to share one thread (to facilitate dynamic scaling)
Spout & Bolt

Topology config – for running on a production Storm cluster
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15Config conf = new Config();
conf.setNumWorkers(1);
// Spout
topologyBuilder.setSpout("my-spout", new MySpout(), 2);
// Bolt
topologyBuilder.setBolt("my-bolt", new MyBolt(), 2)
.shuffleGrouping("my-spout");
StormSubmitter.submitTopology(
"mytopology",
conf,
topologyBuilder.createTopology()
);Creating a Spout
Very often, it suffices to use an existing spout (Kafkaspout, Redis spout, etc), but we usually need to implement our own bolts to realize the specific computation
Creating a Bolt
Two main options for JVM users:
- Implement the IRichBolt or IBasicBolt interfaces
- Extend the BaseRichBolt or BaseBasicBolt abstract classes
BaseBasicBolt
- Auto-acks the incoming tuple at the end of its execute() method
- With the right type of Spout (reliable one), “at-least-once” processing guarantee for each tuple is already supported automatically (and implicitly)
- These bolts are typically simple functions or filters
BaseRichBolt
- Allow one to specify complex tuple-anchoring/ack mechanism explicitly
- Need to use this type of bolt if one wants “at-most-once”, i.e. no guarantee in tuple-processing
- You must – and are able to – manually ack() an incoming tuple
- Can be used to delay acking a tuple, e.g. for algorithms that need to work across multiple incoming tuples
Extending BaseRichBolt:
execute(): focus most of the attention when implementing the bolt or trying to understand someone else’s bolt1
2
3
4
5
6
public void execute(Tuple tuple) {
Integer inputNumber = tuple.getInteger(0);
collector.emit(tuple, new Values(inputNumber * 2)); // auto-boxing
collector.ack(tuple);
}prepare(): prepare () acts as a “second constructor” for the bolt’s class
Because of Storm’s distributed execution model and serialization,prepare()is often needed to fully initialize the bolt on the target JVM1
2
3
4
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
this.collector = collector;
}declareOutputFields(): tells downstream bolts about this bolt’s output format
You will use this information in downstream bolts to “extract” the data from the emitted tuples. If your bolt only performs side effects (e.g. talk to a DB) but does not emit an actual tuple, override this method with an empty{}method1
2
3
4
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("doubled-number"));
}
Topology
Creating a Topology:
- When creating a topology you’re essentially defining the DAG – that is, which spouts and bolts to use, and how they interconnect
TopologyBuilder.setSpout(): Use spoutTopologyBuilder.setBolt(): Use boltshuffleGrouping(): Groupings between spouts and bolts
- It is necessary to specify the initial parallelism of the topology. Only some aspects of parallelism can be changed later, i.e. at run-time
- We can change the #executors (threads)
- We cannot change #tasks, which remains static during the topology’s lifetime
- When creating a topology you’re essentially defining the DAG – that is, which spouts and bolts to use, and how they interconnect
Submitting a Topology:
submit a topology either to a “local” cluster or to a real cluster
LocalCluster.submitTopology()StormSubmitter.submitTopology()orStormSubmitter.submitTopologyWithProgressBar()
A
StormTopologyis a static, serializable Thrift data structure. It contains instructions that tell Storm how to deploy and run the topology in a cluster- The
StormTopologyobject will be serialized, including all the components in the topology’s DAG - Only when the topology is deployed (and serialized in the process) and initialized (i.e. prepare() and other life cycle methods are called on components such as bolts) does it perform any actual message processing
Running a Topology
To run a topology, it is necessary to first package the code in to a “fat jar”
1
storm jar all-my-code.jar com.miguno.MyTopology arg1 arg2
After running
- The topology will run forever or until it is killed
- Storm will guarantee that no data (tuple) is lost, even if machines go down and messages are dropped (as long as you don’t disable this feature)
- But if you store states using your own variables in the bolts/spouts, the state information would be lost when the bolts/spouts die/ crashes
- Storm will automatically restart failed tasks, and even re-assign tasks to different machines if e.g. a machine dies.
Word Counting

1 | TopologyBuilder builder = new TopologyBiulder(); |
At Least Once
Tuple tree:

- A spout tuple is not fully processed until all tuples in the tree have been completed
- If the tuple tree is not completed within a specified timeout, the spout tuple is replayed
- Uses acker tasks to keep track of tuple progress
- Reliability API for the user:
1
2
3
4
5
6
7public void execute(Tuple tuple) {
String sentence = tuple.getString(0);
for(String word: sentence.split(" ")) {
_collector.emit(tuple, new Value(word)); // Anchoring creates a new edge in the tuple tree
}
_collector.ack(tuple); // Marks a single node in the tree as complete
}
If there is a failure
- can double process events
- This is not so critical if you have something like Hadoop to back you up and correct the issue later
- Or if you are looking at statistical trends and replay does not happen that often
- This requires you to have a spout that supports replay. Not all messaging infrastructure does
However, the replay will lead to over-counting ()
Exactly Once - Transactional Topologies
- Transactional Topologies provide a strong ordering of processing
- A small batch of tuples are processed at a time
- Each batch is either completely succeeds or completely fails
- Each batch is “committed” in order
- Partial processing is pipelined
- Requires the spout to be able to replay a batch
Distributed Remote Procedure Call
- It turns an RPC call into a tuple sent from a spout
It takes a result from that and send it back to the user

Examle: Computing “Reach” of a URL on the fly (no. of UNIQUE people exposed to a given URL on Twitter)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32LinearDRPCTopologyBuilder builder = new LinearDRPCTopologyBuilder("reach");
builder.addBolt(new GetTweeters(), 3);
builder.addBolt(new GetFollowers(), 12).shuffleGrouping();
builder.addBolt(new PartialUniquer(), 6).fieldsGrouping(new Fields("id", "follower"));
builder.addBolt(new CountAggregator(), 2).fieldsGrouping(new Fields("id"));
public static class PartialUniquer implements IRichBolt, FinishedCallback {
OutputCollector _collector;
// Keep set of followers for each request id in memory
Map<Object, Set<String>> _sets = new HashMap<Object, Set<String>>();
// Update followers set when receive a new follower
public void execute(Tuple tuple) {
Object id = tuple.getValue(0);
Set<String> curr = _sets.get(id);
if (curr == null) {
curr = new HashSet<String>();
_sets.put(id, curr);
}
curr.add(tuple.getString(1));
_collector.ack(tuple);
}
// Emit partial count after receiving all followers for a request id
public void finishedId(Object id) {
Set<String> curr = _sets.remove(id);
int count = 0;
if (curr != null) count = curr.size();
_collector.emit(new Values(id, count));
}
}
Trident
- Trident is a high-level abstraction for doing Real- Time computing on the top of Storm
- Provides Exactly-Once semantics like transactional topologies
- In Trident, state is a first class citizen, but the exact implementation of state is up to you
- Provides a high level API (similar to cascading for Hadoop)
Conclusion
- Distribute Code and Configuration
- Robust Process Management
- Monitors Topologies and Assign Failed Tasks n Provide Reliability by Tracking Tuple Tree
- Routing and Partitioning of Streams
- Serialization
- Fine-grained Performance Statistics/ Status of Topologies
Architecture
- Nimbus
- Master node
- Manage Topologies; Distribute Code; Assign Tasks; Monitor Failure
- Supervisor
- Runs on Slave nodes (aka Worker nodes); listen to assignment and then launch & manage Worker (JVM) processes
- Coordinate with Zookeeper for Fault-Tolerance/ Synchronization, etc
- Zookeeper
- Store operational States & Statistics
- Cluster Coordination
- Service Discovery
| Hadoop v1 | Storm | Functions in Storm |
|---|---|---|
| JobTracker | Nimbus (only 1) | distributes code around cluster |
| assigns tasks to machines/supervisors | ||
| failure monitoring | ||
| TaskTracker | Supervisor (many) | listens for work assigned to its machine |
| starts and stops worker processes as necessary based on Nimbus | ||
| MR job | Topology | processes messages forever (or until you kill it) |
| a running topology consists of many worker processes spread across many machines |
ZooKeeper
Storm requires ZooKeeper, not for message passing, but used for coordination purposes, and to store state and statistics
- Register + discover Supervisors, detect failed nodes, …
- This allows Storm’s components to be stateless
ZooKeeper also be used for heartbeats and store the recent task errors
Fault Tolerance
Nimbus (master node) dies
- If Nimbus is run under process supervision as recommended (e.g. via supervisord), it will restart like nothing happened
- While Nimbus is down:
- Existing topologies will continue to run, but you cannot submit new topologies.
- Running worker processes will not be affected. Also, Supervisors will restart their (local) workers if needed. However, failed tasks will not be reassigned to other machines, as this is the responsibility of Nimbus
Supervisor (slave node) dies
- If Supervisor run under process supervision as recommended (e.g. via supervisord), will restart like nothing happened
- Running worker processes will not be affected
Worker process dies
- It’s parent Supervisor will restart it. If it continuously fails on startup and is unable to heartbeat to Nimbus, Nimbus will reassign the worker to another machine
Hardware Specs
ZooKeeper
- Preferably use dedicated machines because ZK is a bottleneck for Storm
- I/O is a bottleneck for ZooKeeper
- Preferably run ZK ensembles with nodes >= 3 in production environments so that you can tolerate the failure of 1 ZK server
Nimbus aka master node
- Comparatively little load on Nimbus, so a medium-sized machine suffices
Storm Slave nodes (aka Worker nodes)
- Exact specs depend on anticipated usage – e.g. CPU heavy, I/O heavy, …
- More CPU cores is usually better – the more you have the more threads you can support (i.e. parallelism). And Storm potentially uses a lot of threads
- Memory is highly specific to actual use case
Issues
Scalability Bottlenecks
State Storage (ZooKeeper), limited to the disk write speed
- solution: Pacemaker - allows in-memory store for worker heartbeats
Storm round-robin scheduling
- solution: Resource & Network Topography Aware Scheduler
One slow node slows the entire topology
Scheduling (Especially on Large Clusters)
Resource Isolation / Utilization

