Speed, reliability and increased data processing potential

Data processing – thinking in hardware and software

James Stanier
Thinking illustration via Shutterstock

Torrents of data, high throughput and no downtime – it’s understandable that younger programmers will struggle to deal with the requirements of today’s stack. The best backend developers are the ones that think like hardware engineers, says analyst Dr. James Stanier.

I remember learning about hardware when I was a Computer Science undergraduate. It was taught mostly separately from software with both subjects residing in different modules on the curriculum. To students without much industry experience, it can be easy to think that hardware and software are extremely different subject areas; the former populated with stuffy electronic engineers and silicon, and the latter being where the real computer science happens: data structures, algorithms and code.

I find that the best backend developers are the ones that think in hardware as much as software. Working with large amounts of data, in both streaming and batch modes, is becoming a big area of computer science in industry. Thinking in terms of high throughput, remote services and no downtime can be challenging for developers who haven’t experienced writing this kind of code before. And if that’s not hard enough, I can unscientifically say that the data that we need to consume as an industry only gets bigger over time. Continuing to scale is a challenge, and we have to think of the best ways to utilise our software and hardware so that we can increase data processing capabilities whilst maintaining speed and reliability.

More frequently we find that hardware planning is a bigger part of creating new features than just writing new software. Making good choices up front can not only make your feature extremely reliable and fast, but it can save a large amount of money on your IT budget too.

Data processing

Let’s just jump right in with an example. Where I work at Brandwatch, we provide software that allows people to analyse and explore what is happening online. Customers write search queries that provide them with a personal data stream to explore, in order to understand what people are saying about that topic online.

A lot of our architecture processes data. We analyse matches from the web, classify them in a multitude of ways, and store them. More recently we’ve been analysing the last 24 hours of data with more scrutiny to try and predict whether something interesting is happening: for example, whether a hashtag is beginning to trend, or whether a particular story is being shared. This problem is made more complicated by the fact that we’re not doing global data analysis like Twitter and Facebook do; instead we’re inspecting tens thousands of individual data streams, since every customer’s query in the system is different.

The number of customer’s queries, and therefore data streams, is increasing very rapidly. We currently have 120,000+ live queries, compared to about 70,000 this time last year. The year before that, it was 30,000. You can probably see the issue with scale here.

But let’s not complicate things yet. Let’s start simpler. Writing software to do analysis of one data query is (fairly) straightforward. Let’s do this now with an example of counting the top countries that matches are coming from. Perhaps you could have an application that receives web pages, tweets or Facebook updates, and then for each one you store the country it has been posted from.

public class CountryCounter {

   private Multiset<String> countries = HashMultiset.create();

   public void logCountry(String country) {

   public int occurencesOf(String country) {
       return countries.count(country);

Great! We can then write whatever algorithm we like to find the top country. We could even use a SortedMultiset for this, although enforcing the order of the collection could be expensive with a high rate of inserts. Even though the code is simple, there are a number of considerations when working with extremely large amounts of data. Ideally we don’t want our application to stop running, since the stream of data is never going to stop.

How will we keep the Multiset under control? In this case, aside from a potential future catastrophic political event, the number of countries in the world will never grow explosively. But what if we were tracking the top hashtags, or the top authors? These facets of data often have a very long tail. What impact does that have on RAM over time? Can we store the top items in RAM, but palm off the tail entries to a slower but cheaper storage? How would we cope if we had multiple instances contributing to this global counter? These are all exercises for the reader.

Let’s get back to our specific example, which is processing data for tens of thousands of queries. In this case, we’d want pretty much the same code, but we’d want a Multiset for each search query in our system. They each have a unique ID, so that would be a sensible key to use:

public class QueryCountryCounters {

   private Map<Long, CountryCounter> queryCountryCounters = Maps.newHashMap();

   public void logCountry(long queryId, Match match) {
       CountryCounter countryCounter = queryCountryCounters.get(queryId);

That’ll do – we can assume there will always be a CountryCounter initialised for each query. But what if we want to count 30 other metrics for each query in the system? 30 Multisets for each query is beginning to look more difficult to fit in a sensibly-sized JVM heap, especially as garbage collection becomes slower when there’s more to collect. One solution would be to buy the most powerful machine on the market to run this application, but that’s expensive. Imagine the look on your CFO’s face. It also won’t scale very well if the number of queries continues to grow at an exponential rate.

A better solution is to calculate the required RAM that we require, and divide it by a sensible JVM heap size. That’ll be the number of instances of this application we’ll need to run to solve the problem, as we can have each instance processing a unique set of the total number of queries. This also means you could run instances on cheaper commodity hardware if you wanted to. However, we’ve now created a different problem: if we were running tens or even hundreds of instances, how will they know which queries they should be working on?

Coordinating tasks with Apache Zookeeper and Curator

Leader election is a method of deciding which process is the designated assignee of a task in a distributed system. You can harness the power of leader election by using Apache Zookeeper and Curator. We’ll assume from now that you’ve got a Zookeeper quorum running, but if you need some assistance then do look at the documentation on the Zookeeper website.

Zookeeper looks a bit like a file system, and you interact with data at specific paths, e.g. /foo/bar. It’s up to you to decide how you name and store data. Each item in the “filesystem” is a node, most commonly called a znode to make it clear that we’re talking about Zookeeper. These znodes can also be ephemeral; that is, that when a connection is lost with the client that created them, the ephemeral nodes are deleted also.

First, we’ll write some code to tell Zookeeper that we have a query that needs processing by our instances. We might want to write a new application that manages the creation and deletion of queries, since it only needs to happen in one place. Creating an instance of Curator in your code is simple:


Then here’s a method to create a new node at a specified path:

public void createZNode(String queryId) {
       try {
           client.create().forPath("/queries/" + queryId);
       } catch (NodeExistsException e) {
           log.warn("Node {} was already created.”, queryId);

If a query gets removed from the system, then the code looks pretty similar:

public void removeZNode(String queryId) {
       try {
           client.delete().forPath("/queries/" + queryId);
       } catch (NoNodeException e) {
           log.warn("Node {} was already deleted.”, queryId);

Electing a leader

Next, in the code for our counters, which will be running in multiple instances, we will listen for changes at the path. Firstly, let’s use the LeaderLatchListender interface to define what happens when we win or lose leadership for a query. We’ll assume that the createDataStructure() method initialises the Multisets we defined earlier and inserts the HashMap entry for that query. We’ll also assume that removeDataStructure() removes it, allowing it to be garbage collected.

public class WorkerLeaderLatchListener implements LeaderLatchListener {

   public void isLeader() {

   public void notLeader() {

Next we’ll write a class that uses PathChildrenCacheListener to watch the parent node that is having child nodes added and removed by our other application, and it will receive callbacks via the childEvent method whenever this happens. Depending on the event, it will create or remove the LeaderLatchListener implementation that we’ve just written.

public class WorkerManager implements PathChildrenCacheListener {

   private Map<Integer, LeaderLatch> leaderLatches = newHashMap();

   public void initialise() throws Exception {
       List<ChildData> currentData =
       for (ChildData childData : currentData) {
           long queryId = parseQueryIdFromPath(childData.getPath());

private List<ChildData> initialisePathChildrenCache() throws Exception {
       return pathChildrenCache.getCurrentData();

   public void childEvent(CuratorFramework client,
                          PathChildrenCacheEvent event) {
       ChildData childData = event.getData();
       switch (event.getType()) {
       case CHILD_ADDED:
           long queryId = parseQueryIdFromPath(childData.getPath());
       case CHILD_REMOVED:
		long queryId = parseQueryIdFromPath(childData.getPath());
           // There are other cases to deal with, such as RECONNECT.


   private boolean haveLeaderLatchForQuery(int queryId) {
       return leaderLatches.containsKey(queryId);

   private void startLeaderElection(final int queryId) {
       String leaderPath = "/queries/" + Integer.toString(queryId);
       LeaderLatch leaderLatch = createLeaderLatch(queryId, leaderPath);
       attemptToGetLeadership(queryId, leaderLatch);

   void attemptToGetLeadership(final int queryId, LeaderLatch leaderLatch) {
       LeadershipAttempt leadershipAttempt = new LeadershipAttempt(leaderLatch);

   LeaderLatch createLeaderLatch(final int queryId, String leaderPath) {
       LeaderLatch leaderLatch = new LeaderLatch(client, leaderPath);
       LeaderLatchListener leaderLatchListener = new WorkerLeaderLatchListener(queryId,
               workerContainer, workerRefusals, maximumWorkersAllowed);
       try {
       } catch (Exception e) {
           log.error("Error when starting leadership election", e);
       leaderLatches.put(queryId, leaderLatch);
       return leaderLatch;

   void shutdown() throws IOException {
       for (LeaderLatch leaderLatch : leaderLatches.values()) {


And that’s about it! The instances will now distribute work amongst themselves. If one instance dies, the queries that it was processing will now fail over to another instance. But what about the historical data that was being held in RAM in the other instance? Well, that’s a problem for another time, I guess.

SEE ALSO: Analysing 1,600 human hearts with Big Data

We’re increasingly using distributed election of tasks in our infrastructure to allow us to horizontally scale applications. For example, using the above code, you can spin up five more instances and they would automatically join and participate in the leader election process. Magic.

James Stanier
Dr. James Stanier is Head of Analytics at Brandwatch, a global social media monitoring company. His team work on finding actionable insights in data for the Brandwatch platform.

1 Comment
Inline Feedbacks
View all comments
Philip Stovall
Philip Stovall
2 years ago

Thousands of 4 x 6 enrollment cards: transform cards into data from which a software can identify community concerns and family ancestory.