FOUNDING PRICING · 40% OFFfor the first 1,000 members · from ₹95/month
ArchitectureInstagram10 min read

How Instagram Generates IDs: Sharding on PostgreSQL

How Instagram split its data into thousands of logical shards on a few PostgreSQL servers and built 64-bit, time-sortable IDs inside the database itself.

ShareXLinkedInWhatsApp
A hand holding a smartphone sideways against a sunset over water, with the same sunset shown on the phone's screen.
A hand holding a smartphone sideways against a sunset over water, with the same sunset shown on the phone's screen. Photo: Debraj. Maji, CC BY-SA 4.0, via Wikimedia Commons.

When Instagram outgrew a single PostgreSQL database, it had to answer two questions at once: how to spread rows across many servers, and how to give every row a unique ID when no single server sees every insert. Its answer, described in a short engineering post dated December 2012, was to create thousands of logical shards on a handful of machines and to build a 64-bit, time-sortable ID inside the database with a few lines of stored procedure.

The whole design fits in your head. There is no new service, no coordination protocol and no extra network hop, and every limit of the scheme can be worked out with plain arithmetic.

A diagram of a 64-bit ID split into 41 bits of time, 13 bits of logical shard id and 10 bits of sequence, with the database clock, a per-schema constant and a sequence feeding the three fields, and the worked example from Instagram's post below.

The problem: one counter does not survive sharding

The post opens with the load at the time: more than 25 photos and 90 likes every second. Instagram's application servers ran Django with PostgreSQL behind them. The team wanted the important data to keep fitting in memory, so it began to shard: to split the data into many smaller buckets, each holding a part of it. It evaluated a few NoSQL systems and decided that sharding across a set of PostgreSQL servers suited it best.

Sharding breaks the simplest ID scheme there is. On one database, an auto-incrementing primary key works because one counter sees every insert. With inserts landing on many databases at the same moment, each one has its own counter, and they all hand out 1, 2, 3 and so on. Two photos on two shards would share an ID.

Before choosing a fix, Instagram wrote down three requirements:

  • Sortable by time. A list of photo IDs should be sortable into creation order without fetching anything else about the photos.
  • 64 bits, ideally. Smaller IDs mean smaller indexes, and they store better in systems such as Redis.
  • As few new moving parts as possible. The post credits much of Instagram's ability to scale with very few engineers to choosing simple solutions that the team understood and trusted.

The third requirement is the one that decides the design.

The three options Instagram considered

The post lists three existing approaches, with what it liked and disliked about each.

ApproachExample named in the postForAgainst
Generate in the applicationUUIDs, MongoDB's 12-byte ObjectIdEvery thread generates IDs independently, so there is no shared point of failure or contentionNeeds 96 bits or more for a sound uniqueness guarantee; some UUID types are random and have no natural order
A dedicated ID serviceTwitter's Snowflake64 bits, time first, survives the loss of nodesNew servers plus ZooKeeper to deploy, monitor and keep alive
Database ticket serversFlickrDatabases are well understood and scale predictablyCan become a write bottleneck; extra machines to administer; one server is a single point of failure, and with several the IDs are no longer guaranteed to sort by time

Snowflake is a network service that hands out 64-bit IDs. Twitter's own description gives the layout as 41 bits of millisecond timestamp, 10 bits of machine ID and a 12-bit sequence number. Because the timestamp sits in the most significant bits, IDs sort roughly by time. Instagram said this came closest to what it wanted. The objection was not the format but the operations: an ID service is one more system to run.

Flickr's ticket servers are MySQL databases whose only job is to hand out the next number. To avoid a single point of failure, Flickr runs two, one issuing odd numbers and one issuing even numbers, and the application alternates between them. Flickr's post admits that the two drift apart, which is exactly the loss of time ordering that Instagram wanted to avoid.

Four rows comparing where an ID is made: in the application, in a dedicated ID service with ZooKeeper, in a pair of ticket databases, and inside the database shard itself, which is the option Instagram chose.
Where the ID is made in each approach

Instagram kept Snowflake's idea, a timestamp followed by an identity followed by a sequence, and moved it into a place it already had to run anyway: PostgreSQL.

The design: thousands of logical shards, a few machines

The first half of the design is about where rows live. Instagram's system has several thousand logical shards, mapped in code to far fewer physical database servers.

A logical shard is a label, not a machine. A row is assigned to a logical shard once, by a rule such as taking the user ID modulo the number of logical shards. The post's example uses 2,000 logical shards and user 31341, which gives shard 1341. Separately, application code holds a map from each logical shard to the physical server that currently hosts it.

The benefit shows up on the day you add hardware. If rows were assigned directly to machines, for instance by user ID modulo the number of servers, then going from two servers to three would change the answer for most users, and most rows would have to move. With logical shards the rule never changes. You move a set of whole logical shards to the new server and update the map. The post describes this as growing from a few servers to many without having to re-bucket any data.

A diagram in which the rule user id modulo 2000 fixes each row's logical shard, two machines first hold 1000 schemas each, and a third machine later takes whole schemas from both while no row changes its logical shard.
Adding a machine moves whole logical shards, not individual rows

To make logical shards cheap, Instagram used a PostgreSQL feature called schemas. This is not "schema" in the sense of a table's column list. In PostgreSQL a schema is a namespace inside a database. One database can hold many schemas, and two schemas can each contain a table with the same name without conflict. By default everything goes into a schema called public.

Each logical shard is one schema, and each sharded table, likes for example, exists once inside every schema. The post's sample schema is named insta5, so the likes for the users in shard 5 would sit in a table inside insta5. Since a schema is an ordinary database object, moving a logical shard and creating its tables can be scripted with standard tools.

A close-up of rack-mounted servers in a data centre, with drive bays and status lights in rows.
Rack-mounted servers at the Wikimedia Foundation in 2012. Illustrative only; these are not Instagram's database machines. Photo: Victorgrigas, CC BY-SA 3.0, via Wikimedia Commons.

The ID: 41 bits of time, 13 of shard, 10 of sequence

The second half of the design is the ID itself. Each one is a 64-bit integer made of three fields:

  • 41 bits for the time in milliseconds since a custom epoch.
  • 13 bits for the logical shard ID.
  • 10 bits for an auto-incrementing sequence, taken modulo 1,024.

Each field is generated inside the shard. The time comes from the database server's clock. The shard ID is a constant written into that schema's copy of the function. The sequence is an ordinary PostgreSQL sequence, one per table per schema.

The post walks through an example. Take the time value 1387263000 milliseconds and shift it left by 23 bits (64 minus 41), which leaves 23 empty bits on the right. Take shard 1341 and shift it left by 10, placing it in the next 13 bits. Suppose the table's sequence has already issued 5,000 values. The next is 5,001, and 5,001 modulo 1,024 is 905, which goes into the last 10 bits. OR the three together:

id = (1387263000 << 23) | (1341 << 10) | 905
   = 11637205501278089

In the database, this is a small PL/pgSQL function per schema. The sketch below follows the logic of the function in the post, with names changed:

CREATE FUNCTION insta5.next_id(OUT result bigint) AS $$
DECLARE
    epoch_ms bigint := 1314220021721;  -- the custom epoch
    shard_id int    := 5;              -- this schema's logical shard
    seq      bigint;
    now_ms   bigint;
BEGIN
    SELECT nextval('insta5.table_id_seq') % 1024 INTO seq;
    SELECT FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) INTO now_ms;
    result := ((now_ms - epoch_ms) << 23) | (shard_id << 10) | seq;
END;
$$ LANGUAGE plpgsql;

Each table then declares its primary key as bigint NOT NULL DEFAULT insta5.next_id(). The application never asks for an ID. It runs an INSERT, the default fires inside the shard, and the new ID comes back in the same round trip through the RETURNING clause.

Two details are worth noticing. The epoch constant in the published function is 1314220021721, which as a Unix time in milliseconds is 24 August 2011. And because the shard ID is embedded in every ID, any service holding an ID can extract bits 10 to 22 and know which logical shard to query, with no lookup table. The post calls this a bonus.

What the bit layout allows and what it costs

Every limit of this scheme can be read off the three field widths. The first two points below come from the post. The rest is arithmetic and reasoning that the post does not spell out.

Throughput. Ten bits of sequence give 1,024 values, so each table in each logical shard can generate 1,024 IDs per millisecond. Against 25 photos per second across the whole system, that is a great deal of headroom. The post does not say what happens if one table exceeds it. Since the sequence simply wraps, a 1,025th insert in the same millisecond would repeat an ID and the primary key constraint would reject it.

Number of shards. Thirteen bits allow 8,192 logical shard IDs, which is room for the several thousand the post mentions. This number is effectively fixed for life, so it has to be chosen generously at the start.

Lifetime. The post says 41 bits of milliseconds give 41 years of IDs. Two to the power 41 milliseconds is about 69.7 years, which matches the 69 years Twitter quotes for Snowflake's 41-bit timestamp. There is one more subtlety: the three fields use all 64 bits, and PostgreSQL's bigint is signed. By our arithmetic the top bit of the time field becomes the sign bit, so IDs would turn negative about 34.8 years after the epoch. They would still be unique, but they would sort before every older ID.

Ordering is approximate across shards. Within one table in one shard, IDs rise with time. Across shards, two IDs created in the same millisecond are ordered by shard number, not by which happened first, and each server stamps IDs with its own clock. For a photo feed, ordering to within a few milliseconds is plenty. For anything that needs a strict global order, it is not.

The clock matters. The scheme assumes a server's clock does not jump backwards. If it did, new IDs could sort before older ones for a while. The post does not discuss this case.

The computer science underneath

Unique IDs in a distributed system. The core difficulty is producing identifiers that never collide without a single authority handing them out. The standard trick is to divide the ID space in advance: give each generator its own slice, here the shard ID field, and let it number freely within that slice. Our lesson on unique ID generation compares auto-increment, UUIDs, ticket servers and Snowflake, which are the same options Instagram weighed.

Sharding and the shard key. Splitting data across servers means choosing a key that decides where each row goes, and living with the consequences. Queries that stay inside one shard are cheap. Queries that span shards are not. Sharding and replication covers the basics, and shard keys, resharding and cross-shard queries explains why a level of indirection between the key and the machine, such as logical shards, makes growth far less painful.

Primary keys and index locality. A primary key is stored in a B-tree index. Keys that increase over time are appended at the right-hand edge of the tree, which keeps recently used pages in memory. Random keys land all over it. That is the practical cost of random UUIDs and part of why Instagram wanted time first. The lesson on choosing a primary key works through this trade-off.

Sorting without a second column. If the ID already encodes time, then "the next 20 photos older than this one" becomes a range scan on the primary key. That is the idea behind keyset pagination, and it is what Instagram's first requirement was really asking for.

What an interviewer could ask from this

Why not use auto-increment on each shard? Each shard has its own counter, so different shards would issue the same numbers. IDs would be unique per shard but not across the application.

Why did Instagram not adopt Snowflake, given that its ID looks so similar? The format suited them. The operational cost did not. Snowflake needs its own servers and ZooKeeper, and Instagram wanted no new moving parts. It put the same idea inside PostgreSQL, which it already ran.

What is a logical shard and why have thousands of them on a few machines? A logical shard is a fixed bucket that a row is assigned to once. Many logical shards share one machine. To add capacity you move whole logical shards and update a map, so no row's bucket and no ID ever changes.

How many IDs per second can this scheme produce? 1,024 per millisecond per table per logical shard, which is roughly a million per second for one table in one shard, multiplied by the number of shards.

Are these IDs strictly ordered by time? Within one table in one shard, yes, as long as the clock moves forward. Across shards, only approximately, to within the clock difference between servers and the resolution of one millisecond.

Takeaways

  • Sharding removes the one counter that auto-increment depends on, so ID generation has to be designed, not assumed.
  • A timestamp in the high bits, a generator identity in the middle and a sequence in the low bits gives IDs that are unique, compact and roughly sortable by time.
  • Thousands of logical shards mapped to a few machines let you add hardware by moving buckets, without re-bucketing rows.
  • Instagram chose the option with the fewest new systems to run, and accepted fixed field widths as the price.
  • Every limit of a bit-packed ID is arithmetic on its field widths, so work those limits out before you ship the layout.

Sources

  1. Instagram Engineering: Sharding & IDs at Instagram (Wayback Machine copy of the post dated 30 December 2012)
  2. Twitter: Snowflake README, 2010 release (ID layout and requirements)
  3. Flickr Code: Ticket Servers, Distributed Unique Primary Keys on the Cheap (8 February 2010)
  4. PostgreSQL documentation: Schemas

Written by the Codevizag Academy team

An independent explainer built from the public sources listed above. Codevizag Academy is not affiliated with Instagram. Found a mistake? Write to support@codevizag.com.

More case studies

Understood it? Now prove it.

The lessons behind this case study are free, and 20 problems a month are judged on real test cases at no cost.

Start solving free