Bugpit

Lessons › Real apps

Instagram: 3 billion people

Instagram says 3 billion people use it every month. You're running a small slice of that: 30,000 req/s. Most of it is photos. Every like, comment and post is a write, and right now photos come through your own servers and every write lands on one database.

Play this level

Part of Bugpit Pro. It runs in your browser: build the design, press Run, and watch what breaks.

The lesson

Start with the photos. They're big and they never change, so they don't belong on your servers. Keep them in object storage and let a CDN hand out copies from close to each person.

Then the writes. Instagram's engineers wrote that when one PostgreSQL machine couldn't take them, they split the data into thousands of small logical shards, spread over a few machines. Each user's data lives in one shard, so most queries still touch one place.

Shards break one thing: the id counter. No single machine can hand out 1, 2, 3 any more. Instagram's ids pack three parts into one number: 41 bits of time, 13 bits naming the shard, and a 10 bit counter. Any shard makes ids by itself, and they still sort by time.

Last, the feed. When someone posts, their followers' feeds need the new photo. That work is done in the background: the post goes into a queue, and workers add it to each follower's feed. This is fan out on write.

What you have to achieve

30,000 requests a second at the busiest hour, 10% of them writes and 70% static files.

What you learn

Photos never touch your servers now, writes are spread over shards, and feeds fill in the background. Fan out on write has one weak spot: an account with 100 million followers. For those, feeds are built when people open the app instead, which is fan out on read. Real systems mix both.

The real numbers behind it

Check yourself

Instagram's ids pack time, shard and a counter into one number. Why?

Show the answer

Any shard can make ids by itself, and they still sort by time. With shards, no single machine can count 1, 2, 3. Each shard makes unique ids on its own.

What is fan out on write?

Show the answer

Adding a new post to each follower's feed in the background. Workers fill feeds when someone posts. For accounts with huge followings, feeds are built on read instead.

Try it yourself

More in Real apps

← Swiggy: New Year's Eve ChatGPT: 2.5 billion prompts a day →