Home > Articles > Programming

Saving the Failwhale: The Art of Concurrency

Dhanji R. Prasanna shows how to make a successful jump from single-user development to the volumes of users and inputs in the production realm. The trick is well-designed concurrency, based on successfully handling (or avoiding) the extreme resource contention that causes many programs to fail.
Like this article? We recommend

Like this article? We recommend

One of the most challenging bits of server-side programming is when you go from the safe, comfortable environs of the single-user development stage to the wild, unpredictable realm of production. With its large volumes of users and odd, arbitrary, and unforeseen data inputs, it can be a scary transition indeed.

The key to making this jump successful is a robust and well-designed system of concurrency. This rule applies to web applications, mobile applications with back-end components, and even to services that have no users at all (in the traditional sense) but must contend with a large amount of data being processed simultaneously; for example, when a brokerage firm or a bank clears checks in a batch at the end of the day. This is where the experience of senior engineers really comes into its own. Everyone knows the story of an application working perfectly during the development phase, only to melt under even infinitesimal traffic. Even if you haven't lived through this experience yourself, you've heard about it. The social network Twitter has even coined a special phrase for it: the failwhale.

Of course, Twitter was the victim of several issues, including simply not having enough capacity to handle its rising traffic. However, it's a good emblem of the kinds of problems that new projects face when they're forced to grow up fast. One side of this problem is a lack of capacity; that is, the traffic growth vastly exceeded what was expected. The other side, one that's often ignored or forgotten, is the poor utilization of existing resources. In other words, poor concurrency.

In this article I'll summarize a few techniques that I've found useful over the years in laying the groundwork for good utilization of resources. The key is always concurrency.

Handling Unavoidable Resource Contention

At its core, effective concurrency involves the idea that there's always a discrepancy between the speed of resources in a system. For example, the CPU is generally faster than RAM, and RAM is generally faster than a hard disk. The result of these discrepancies is that resources belonging to one tier are accessed more slowly than they're required in other (faster) tiers. This design creates a bottleneck, where faster tiers of the application are constantly outpacing the slower tiers, and thus contending for the same resources.

In some cases, contention is unavoidable. Some resources are just slow, and we must wait for them. The secrets to good concurrency in this case are 1) ensuring that these slower resources are rare, and 2) during such waiting periods, giving the faster tiers other work to do so that they continue being utilized well.

Synchronized Versus Concurrent

Even systems with low resource contention perform poorly under load if their architecture isn't well suited for concurrency. Symptoms include the overuse of synchronization constructs such as locks and mutexes. In Java, overuse of the synchronized keyword is a good example.

Consider the following very common data structure—the hash table. A hash table is a fantastic tool for storing pairs of names and values for fast lookup. These tables perform incredibly well (in constant time, asymptotically speaking) for both inserting keys and reading back their associated values:

public class UserService {
  private Map<String, User> cache = new HashMap<String, User>();

  public void register(User user) {
    cache.put(user.getName(), user);
    // etc.
  }
}

In this example, we're using the hash table—called a HashMap in Java—as a cache. However, a HashMap by itself is not thread-safe. If register() is called concurrently by two or more threads, the underlying data structure will become corrupt—the worst possible outcome for any piece of critical code.

To fix this problem, people often use the synchronized version of the HashMap:

public class UserService {
  private Map<String, User> cache = Collections.synchronizedMap(new HashMap<String, User>());

  public void register(User user) {
    cache.put(user.getName(), user);
    // etc.
  }
}

This approach solves the data-corruption issue, but it also introduces a major new issue—lock contention. Any cache access will now occur under an exclusive lock, meaning that only one thread at a time will be able to write to the cache or read from it. This is a horrible situation if you have hundreds or even dozens of concurrent users and modern multicore CPUs. The hardware is wasted and user experience suffers.

The solution to this issue is to use a ConcurrentHashMap:

public class UserService {
  private Map<String, User> cache = new ConcurrentHashMap<String, User>();

  public void register(User user) {
    cache.put(user.getName(), user);
    // etc.
  }
}

The code now frees up, allowing concurrent access to competing threads. However, the ConcurrentHashMap isn't some magical construct; it's important to know how and why it works, so you know when to use it and what its benefits are.

The ConcurrentHashMap doesn't actually do away with locks. It still uses them, but it uses more than the single global lock, so that threads gain some measure of concurrency. (It also uses some tricks to prevent locking when only reading from the HashMap, but let's leave that discussion for another time.) By dividing the entire key space into several partitions, the ConcurrentHashMap statistically ensures that multiple writing threads interfere with one another infrequently. It reserves a separate lock for each of these partitions, so that multiple threads writing to the map are likely to access different partitions (taking separate locks) and therefore process their data simultaneously. This technique is known as lock-striping.

For ConcurrentHashMaps, 8–16 stripes is plenty for handling most concurrency use cases. (As a rule, this number is proportional to the number of CPU cores in a system.)

As a design pattern, this kind of concurrency can be applied to a great number of use cases. One of my favorites is the producer/consumer queue.

Improving Utilization

A traditional producer/consumer queue is a common design pattern that's used to handle use cases where tasks are generated sporadically by a small number of agents, and consumed uniformly by a large number of workers that perform the produced tasks. A coffee shop is a good analogy: You usually have one order-taker at the till who sporadically generates tasks (orders for coffee and so forth) for multiple baristas, who in turn operate espresso machines and other equipment to perform the designated tasks (preparing the coffee to fill the orders).

The baristas don't care who ordered the coffee—if one barista is busy, another swoops in to pick up any waiting orders and continue brewing coffee. The coffee orders are held in a queue to be processed as they arrive. This is the quintessential producer/consumer queue. It utilizes the available resources (baristas) efficiently, with hardly any contention at all (the tiny amount of time it takes for a barista to pull order tickets from the queue).

This pattern is extremely useful in a variety of computational tasks. Let's take email as an example--checking for new mail generally works like this:

  1. Open your email application (on your iPhone, for instance). The application sends a request for mail to the server.
  2. You wait until the server is contacted, and continue waiting while it performs its own check against a database.
  3. Finally the mail is returned and displayed for you to read.

This whole activity features two forms of contention that scream for better efficiency:

  • You must wait with the mail app open, spinning, while the server is being checked.
  • The server is expending resources waiting on its own database to read the data off disk and return it.

Applying our learned design patterns, we can improve both of these issues easily. On the client, we institute a periodic check (say, once every 15 minutes), which sends a simple task to the server: "Notify me if new mail has arrived since the last time I checked." This is our task producer. The server then performs the busy work of checking for mail. It sends a notification back to the app if new mail is available; if no new mail exists, it does nothing. This is the task consumer. On smartphones, this structure is sometimes called push notification.

In more practical terms, we can see this structure modeled on the server using a producer/consumer queue. The server receives a number of email check requests from various clients and places them in a queue:

public class EmailChecker {
  private ExecutorService exec = Executors.newFixedThreadPool(8);

  // producer
  public void checkForEmail(final Client details) {
    exec.submit(new Runnable() {
      public void run() {
        perform(newCheckRequest(details)));
      }
    });
  }

  // consumer
  public void perform(Request req) {
    if (req != null) {
      NewMail mail = checkDatabase(req);

    if (mail != null)
      notify(req, mail);
    }
  }
}

So here we have two methods—one that adds tasks to the queue, and another that pops off the tasks and checks against the database, sending a notification if necessary.

Two Methods for Addressing Resource Contention

Concurrency comes into play when we decide how to distribute our resources. By using an ExecutorService (essentially a thread pool accompanied by a task queue), we can schedule eight threads to run all the time processing email check requests. This approach ensures that we process a maximum of eight requests simultaneously against the database. By doing this, we convert the sporadic, patchy swaths of check requests from apps into a smooth, uniform, and predictable load on the CPU and database. Without this setup, if there was a sudden influx of check requests (everyone woke up in the morning and turned on their phone, for example), we'd be looking at a failwhale scenario, where the load on the database would have exceeded its capacity.

This is the same concurrency design pattern, but its purpose is inverted—rather than applying it to improve utilization of our resources, we're using it to reduce spiky load on the database. As you may have noticed, both applications are intended to reduce resource contention, but are applied from different angles and have different consequences. This design pattern is often referred to as an "asynchronous processing model."

Summary

Concurrency design patterns are vital to any robust system design. Understanding specific, low-level constructs like concurrent data structures is just as important as knowing broad, "birds-eye" architectural decisions such as producer/consumer models. Mastering concurrency at both levels gives you the ultimate harpoon against the failwhale.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020