Batching Calls

Problem

I have a bunch of calls I need to make using the API, and I’d really like to batch them to get better performance.

Solution

Facebook has recently released a Batch API that does exactly that. The batching support is really easy to use and basically consists of wrapping the calls you want to make in beginBatch() and endBatch() statements.

If you were previously running this code as individual calls:

$friends = $facebook->api_client->friends_get();
$notifications = $facebook->api_client->notifications_get();

you could do the same thing as a batch by doing this:

$facebook->api_client->begin_batch();
$friends = &$facebook->api_client->friends_get();
$notifications = &$facebook->api_client->notifications_get();
$facebook->api_client->end_batch();

You won’t see any significant performance gains on two calls, but you should if you push the Batch API to its limit and run 20 calls in a batch. See the Discussion for more information about what’s really happening.

Discussion

The Batch API is currently in beta, so remember that you probably shouldn’t build production code on it without being very careful, and you should report any bugs you might find into the Facebook Bug Tracker at http://bugs.developers.facebook.com.

Batching is considerably more efficient because it saves you roundtrips to the server on each call, and it lets Facebook process up to 20 calls in parallel at the same time. If you made each of those calls individually, you’d have to do them in series and would have ...

Get Facebook Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.