# Futures for C++11 at Facebook

Futures are a pattern for expressing asynchronous computations in a natural and composable way. This blog post introduces Folly Futures, an implementation of futures for C++11 that we use at Facebook.

# Why asynchrony?

Consider a service A that talks to another service B. If A blocks while waiting for a reply from B, then A is synchronous. A blocked thread is idle; it cannot service other requests. Threads are heavyweight — switching threads is inefficient, they have considerable memory overhead, and the OS will bog down if you make too many of them. The result is wasted resources, reduced throughput, and increased latency (because requests are in a queue, waiting to be serviced).

It is more efficient to make service A asynchronous, meaning that while B is busy computing its answer, A has moved on to service other requests. When the answer from B becomes available, A will use it to finish the request.

# Synchronous code and asynchronous code compared

Let's consider a function fooSync that does a basic computation foo fully synchronously, and a function fooAsync that does the same work asynchronously. fooAsync takes both an input and a callback, which is called once the answer is available.

1 template <typename T> using Callback = std::function<void(T)>;
2
3 Output fooSync(Input);
4 void fooAsync(Input, Callback<Output>);


This is the traditional way of expressing asynchronous computation. (Older C/C++ asynchronous libraries would take a function pointer and a void* context argument, but now that C++11 supports closures, an explicit context argument is not required.)

Traditional asynchronous code is more efficient than synchronous code, but it is not as easy to read. Compare the synchronous and asynchronous versions of a function that implements a multiFoo computation, which does foo for every element in an input vector:

 1 using std::vector;
2
3 vector<Output> multiFooSync(vector<Input> inputs) {
4   vector<Output> outputs;
5   for (auto input : inputs) {
6     outputs.push_back(fooSync(input));
7   }
8   return outputs;
9 }

 1 void multiFooAsync(
2   vector<Input> inputs,
3   Callback<vector<Output>> callback)
4 {
5   struct Context {
6     vector<Output> outputs;
7     std::mutex lock;
8     size_t remaining;
9   };
10   auto context = std::make_shared<Context>();
11   context->remaining = inputs.size();
12
13   for (auto input : inputs) {
14     fooAsync(
15       input,
16       [=](Output output) {
17         std::lock_guard<std::mutex> guard(context->lock);
18         context->outputs->push_back(output);
19         if (--context->remaining == 0) {
20           callback(context->outputs);
21         }
22       });
23   }
24 }


The asynchronous version is much more complicated. It has to worry about setting up a shared context object, thread safety, and bookkeeping, so it will know when the overall computation is complete. Even worse, though it's not obvious in this example, is that when the computation graph becomes complex, it becomes very difficult to follow the execution path. Programmers need to build up a mental model of the whole service state machine and how it acts with different inputs, and computation flow is not expressed in one place in the code where it can be reviewed. This state of affairs is affectionately referred to as "callback hell."

# Futures

A future is an object that represents the result of an asynchronous computation, which may not yet be available. When the computation is complete, the future may hold either a value or an exception. As an example:

 1 #include <folly/futures/Future.h>
2 using folly::Future;
3
4 // Do foo asynchronously; immediately return a Future for the output
5 Future<Output> fooFuture(Input);
6
7 Future<Output> f = fooFuture(input);
8 // f may not have a value (or exception) yet. But eventually it will.
9 f.isReady();  // Maybe, maybe not.
10 f.wait();     // You can synchronously wait for futures to become ready.
11 f.isReady();  // Now this is guaranteed to be true.
12 Output o = f.value();  // If f holds an exception, this will throw that exception.


So far we haven't done anything std::future can't do. But a powerful aspect of the future pattern is being able to chain callbacks, which std::future doesn't yet support. We express this with the method Future::then :

 1 Future<double> f =
2   fooFuture(input)
3   .then([](Output o) {
4     return o * M_PI;
5   })
6   .onError([](std::exception const& e) {
7     cerr << "Oh bother, " << e.what()
8       << ". Returning pi instead." << endl;
9     return M_PI;
10   });
11
12 // get() first waits, and then returns the value
13 cout << "Result: " << f.get() << endl;


Here we chained then as well as onError to handle any exception that may have been generated. Being able to chain futures turns out to be an important capability. It allows us to compose sequential and parallel computations, express them in one place, and provide clean error handling.

# Sequential composition

If you want to do computations a, b, c, and d asynchronously in that order, with traditional callback programming you end up with callback hell — or, in a language with first-class anonymous functions (like C++11), perhaps the “callback pyramid”:

 1 // the callback pyramid is syntactically annoying
2
3 void asyncA(Output, Callback<OutputA>);
4 void asyncB(OutputA, Callback<OutputB>);
5 void asyncC(OutputB, Callback<OutputC>);
6 void asyncD(OutputC, Callback<OutputD>);
7
8 auto result = std::make_shared<double>();
9 fooAsync(input, [=](Output output) {
10   // ...
11   asyncA(output, [=](OutputA outputA) {
12     // ...
13     asyncB(outputA, [=](OutputB outputB) {
14       // ...
15       asyncC(outputB, [=](OutputC outputC) {
16         // ...
17         asyncD(outputC, [=](OutputD outputD) {
18           *result = outputD * M_PI;
19         });
20       });
21     });
22   });
23 });
24
25 // As an exercise for the masochistic reader, express the same thing without
26 // lambdas. The result is called callback hell.


With futures, sequentially composed using then, the code cleans up nicely:

 1 Future<OutputA> futureA(Output);
2 Future<OutputB> futureB(OutputA);
3 Future<OutputC> futureC(OutputB);
4 // then() automatically lifts values (and exceptions) into a Future.
5 OutputD d(OutputC) {
6   if (somethingExceptional) throw anException;
7   return OutputD();
8 }
9
10 Future<double> fut =
11   fooFuture(input)
12   .then(futureA)
13   .then(futureB)
14   .then(futureC)
15   .then(d)
16   .then([](OutputD outputD) { // lambdas are ok too
17     return outputD * M_PI;
18   });


# Parallel composition

Let's go back to our multiFoo example. Here's what it looks like with futures:

 1 using folly::futures::collect;
2
3 Future<vector<Output>> multiFooFuture(vector<Input> inputs) {
4   vector<Future<Output>> futures;
5   for (auto input : inputs) {
6     futures.push_back(fooFuture(input));
7   }
8   return collect(futures);
9 }


collect is one of the compositional building blocks we provide, which takes a collection of Future<T> and returns a Future<vector<T>> that will complete when all those futures are complete. (The implementation of collect relies on — you guessed it — then.) There are many other compositional building blocks, including collectAny, collectN, map, and reduce.

Notice how this code looks very similar to the synchronous version multiFooSync, above. We don't need to worry about passing context around or thread safety; it is all handled transparently for us by the framework.

# Execution context

Some futures frameworks in other languages provide a thread pool for executing callbacks, so you don't need to worry about the execution context other than to know that it's in some other thread. But C++ developers tend to be writing C++ because they need to control low-level details for performance optimization, and this is certainly true at Facebook. So we provide a flexible mechanism for explicitly controlling the execution context of callbacks, using a simple Executor interface:

1 struct Executor {
2   using Func = std::function<void()>;
3   virtual void add(Func) = 0;
4 };


You can pass an executor to then to dictate that its callback will execute via that executor.

1 a(input).then(executor, b);


In this code, b will be executed via executor, which might be a specific thread, a thread pool, or something even more intriguing. A common use case for this is to move significant CPU work off of the I/O thread to avoid queueing delay for other requests.

# Futures mean never having to forget you're sorry

One pervasive problem with traditional callback code is that it is extremely easy to lose track of errors or exceptional conditions. Programmers must exercise great (even superhuman) discipline to check for errors and take appropriate action, to say nothing of what happens when an unexpected exception is thrown. Futures address this problem by containing either a value or an exception, and exceptions behave like you would expect exceptions to when composing futures, except that it remains within the future monad until handled with onError or released synchronously with, for example, value or get. It's harder (though not impossible) to lose track of an error that should be handled.

# You make me promises, promises

We've seen an overview of how to use futures, but how do we make them? If you need to lift a value into Future, use makeFuture:

1 using folly::makeFuture;
2
3 std::runtime_error greatScott("Great Scott!");
4
5 Future<double> future = makeFuture(1.21e9);
6 Future<double> future = makeFuture<double>(greatScott);


But if you are wrapping an asynchronous operation, you use a Promise:

1 using folly::Promise;
2
3 Promise<double> promise;
4 Future<double> future = promise.getFuture();


When you're ready to fulfill the promise, use setValue, setException, or setWith:

1 promise.setValue(1.21e9);
2 promise.setException(greatScott);
3 promise.setWith([]{
4   if (year == 1955 || year == 1885) throw greatScott;
5   return 1.21e9;
6 });


All together, then, making a long-running synchronous operation asynchronous by spawning another thread might look like this:

 1 double getEnergySync(int year) {
2   auto reactor = ReactorFactory::getReactor(year);
3   if (!reactor) // It must be 1955 or 1885
4     throw greatScott;
5
6   return reactor->getGigawatts(1.21);
7 }
8
9 Future<double> getEnergy(int year) {
10   auto promise = make_shared<Promise<double>>();
11
13     promise->setWith(std::bind(getEnergySync, year));
14   }).detach();
15
16   return promise->getFuture();
17 }


You often don't need promises, even if at first blush it seems like you do. For example, if you already have an executor for your thread pool or can get your hands on one easily, it's easier to just do this:

1 Future<double> future = folly::via(executor, std::bind(getEnergySync, year));


# Case studies

We offer two case studies for how using futures has improved latency, robustness, and code readability at Facebook and Instagram.

Instagram improved the infrastructure for their recommendation service by converting it from synchronous to asynchronous, using futures. The result was a significant drop in tail latencies, and tenfold fewer servers required to achieve the same throughput. They describe the changes they made and the benefits in more detail in their blog post (mirror).

The next case study is a real service that is one piece of constructing the Facebook News Feed. It has a two-stage leaf-aggregate pattern, where a request is broken into many leaf requests that shard to different leaf servers, and then we do the same thing but shard differently based on the results of the first aggregate. Finally, we take both sets of results and reduce them to a single response.

Here is a simplified version of the relevant code:

 1 Future<vector<LeafResponse>> fanout(
2   const map<Leaf, LeafReq>& leafToReqMap,
3   chrono::milliseconds timeout)
4 {
5   vector<Future<LeafResponse>> leafFutures;
6
7   for (const auto& kv : leafToReqMap) {
8     const auto& leaf = kv.first;
9     const auto& leafReq = kv.second;
10
11     leafFutures.push_back(
12       // Get the client for this leaf and do the async RPC
13       getClient(leaf)->futureLeafRPC(leafReq)
14
15       // If the request times out, use an empty response and move on.
16       .onTimeout(timeout, [=] { return LeafResponse(); })
17
18       // If there's an error (e.g. RPC exception),
19       // use an empty response and move on.
20       .onError([=](const exception& e) { return LeafResponse(); }));
21   }
22
23   // Collect all the individual leaf requests into one Future
24   return collect(leafFutures);
25 }
26
27 // Some sharding function; possibly dependent on previous responses.
28 map<Leaf, LeafReq> buildLeafToReqMap(
29     const Request& request,
30     const vector<LeafResponse>& responses);
31
32 // This function assembles our final response.
33 Response assembleResponse(
34     const Request& request,
35     const vector<LeafResponse>& firstFanoutResponses,
36     const vector<LeafResponse>& secondFanoutResponses);
37
38 Future<Response> twoStageFanout(shared_ptr<Request> request) {
39   // Stage 1: first fanout
40   return fanout(buildLeafToReqMap(*request, {}),
41                 FIRST_FANOUT_TIMEOUT_MS)
42
43   // Stage 2: With the first fanout completed, initiate the second fanout.
44   .then([=](vector<LeafResponse>& responses) {
45     auto firstFanoutResponses =
46       std::make_shared<vector<LeafResponse>>(std::move(responses));
47
48     // This time, sharding is dependent on the first fanout.
49     return fanout(buildLeafToReqMap(*request, *firstFanoutResponses),
50                   SECOND_FANOUT_TIMEOUT_MS)
51
52     // Stage 3: Assemble and return the final response.
53     .then([=](const vector<LeafResponse>& secondFanoutResponses) {
54       return assembleResponse(*request, *firstFanoutResponses, secondFanoutResponses);
55     });
56   });
57 }


The legacy version of this service was utilizing an asynchronous framework that allowed only an overall timeout and used the traditional "callback hell" style. Futures made it natural to express the asynchronous computation and use granular timeouts to take more proactive action when some piece is slow. As a result, the service's average latency was reduced by two-thirds, and tail latencies were reduced tenfold. Overall timeout errors were reduced significantly. The code is much easier to read and reason about, and as a result, it is more maintainable.

When developers have the tools to understand and express asynchrony better, they write lower-latency services that are easier to maintain.

# Conclusion

Folly Futures bring robust, powerful, and performant futures to C++11. We hope that you enjoy using them as much as we do. For more information, consult the documentation, docblocks, and code on GitHub.

# Acknowledgements

The team that wrangled Folly Futures into existence is Hans Fugal, Dave Watson, James Sedgwick, Hannes Roth, and Blake Matheny, with contributions from many others along the way. We would like to thank Twitter and particularly Marius, whose tech talk at Facebook on Finagle and Futures inspired the project.