Courses / System Design Interview / Chapter 33
Module 7 · Design Problems II: Rides and Social Feeds · Chapter 33 of 49
Design a Photo-Sharing Service like Instagram
Builds on Non-Functional Requirements: Availability, Scale, Latency and More, Back-of-the-Envelope Estimates, Databases: Choosing, Replicating and Partitioning, Content Delivery Networks, Unique IDs: Sequencers, UUIDs and Snowflake IDs, Distributed Message Queues, Blob Stores, Distributed Search, Sharded Counters, Design a Microblogging Service like Twitter and Design a News Feed. Next up: Design a URL Shortener like TinyURL.
Part 1 · Requirements and estimates
What the service must do
A photo-sharing service lets people upload pictures and look at the pictures of the people they follow. This chapter designs the upload, the processing and the delivery of those pictures, and the ids that let the data spread over many databases.
The functional requirements are: upload a photo with a caption; view a photo at a size that suits the screen; follow other accounts; see a feed of recent photos from the accounts you follow; like and comment on a photo; and delete your own photo. Video, stories, direct messages, search and advertising are out of scope. The ranking of the feed was the subject of the previous chapter, so here the follow feed is simply the newest photos first.
The non-functional requirements shape the rest. Uploads come from phones on slow, unreliable networks, so they must be retried safely. A photo must never be lost once the app says it is posted, which makes durability the strictest requirement. A photo should be viewable by its owner within a few seconds of posting, even if the smaller sizes take a little longer. Pictures must load quickly in every region. The feed and the counts may be a little behind.
The design below is ours. It uses the building blocks from the earlier chapters and makes no claim about how any particular company built its service.
| Question to ask | Answer we assume |
|---|---|
| How many photos a day? | 2 crore new photos a day |
| How big is an upload? | An original of about 3 MB, capped at 5 MB |
| How many sizes are shown? | Four smaller sizes, from 1080 pixels down to a thumbnail |
| How long are photos kept? | Until the owner deletes them; plan for five years of growth |
Storage and delivery
The estimate has two halves, as in the estimates chapter: what we store, and what we send. A single upload becomes five stored objects: the original and four renditions. The scene follows the storage arithmetic.
With a 10+4 erasure code: ≈ 173 PB (1.4 times the data, not 3 times)
Read it as steps
Storage grows by tens of terabytes a day, and the original is most of it.
The scene says the quiet part out loud: almost nine bytes in ten are the original, which no viewer ever receives. That is why the design below keeps originals in a cheaper, slower tier once the smaller sizes exist, and why the next script is worth running with your own sizes.
# Assumptions of ours; change them and rerun. uploads_per_day = 2_00_00_000 # 2 crore new photos a day years = 5 sizes_kb = { # stored size of each rendition "original": 3000, "1080 px": 250, "640 px": 90, "320 px": 30, "thumb 150 px": 8, } day, year = 86_400, 365 print(f"uploads per second, average: {uploads_per_day / day:,.0f}") print(f"uploads per second, peak x3: {uploads_per_day * 3 / day:,.0f}") per_photo_kb = sum(sizes_kb.values()) per_day_tb = uploads_per_day * per_photo_kb * 1000 / 1e12 print(f"stored per photo: {per_photo_kb:,} KB " f"({sizes_kb['original'] / per_photo_kb:.0%} is the original)") print(f"new data per day: {per_day_tb:,.1f} TB")
Python 3.12.10. Save this and the next block together as photo_estimate.py.
total_pb = per_day_tb * year * years / 1000 print(f"after {years} years, one copy: {total_pb:,.1f} PB") print(f"3 full copies: {total_pb * 3:,.1f} PB") print(f"10+4 erasure code (1.4x): {total_pb * 1.4:,.1f} PB") # Delivery: a viewer opens 40 photos a session, mostly small renditions. sessions = 10_00_00_000 # 10 crore sessions a day avg_kb = 0.7 * sizes_kb["640 px"] + 0.3 * sizes_kb["320 px"] egress_tb = sessions * 40 * avg_kb * 1000 / 1e12 print(f"photos viewed per day: {sessions * 40:,}") print(f"data sent per day: {egress_tb:,.0f} TB " f"= {egress_tb * 8e12 / day / 1e9:,.0f} Gbit/s on average")
Continue in the same file.
Reading the numbers
On the upload side, 2 crore photos a day is 231 a second on average and 694 at the busiest second if we plan for three times the average. That is a modest request rate, but not a modest data rate: 694 uploads of about 3 MB is roughly 2 GB arriving every second at the peak. If the application servers had to carry those bytes, they would need a great deal of network and memory for nothing useful. This is the reason for the direct-upload design in the third lesson.
On the storage side, 67.6 TB of new data a day reaches 123.3 PB in five years with one copy. The blob store chapter explained the options: three full copies would be 369.9 PB, while an erasure code with ten data and four parity pieces stores 1.4 times the data and gives 172.6 PB. Durability is the requirement we cannot trade, so the choice is between paying for more copies or accepting a more complex repair path.
On the delivery side, 10 crore sessions of 40 photos is 400 crore views a day. If 70 percent are the 640-pixel size and 30 percent the 320-pixel size, the average view is 72 KB, which is 288 TB a day or about 27 gigabits a second on average. No origin should serve that. The cdn chapter's cache hit ratio argument applies directly: popular photos are served at the edge, and the object store sees only misses.
Using the output, how much of the stored bytes per photo is the original?
- 89 percent: 3,000 of 3,378 KB. The four renditions together are only 378 KB.
Why should the API servers not carry the upload bytes?
- At the peak of 694 uploads a second of about 3 MB each, they would handle roughly 2 GB a second that they do nothing useful with. The phone can send the bytes straight to the object store.
How many photo views a day does the script assume, and how does it turn them into traffic?
- 400 crore views (10 crore sessions of 40 photos). With an average of 72 KB per view that is 288 TB a day, or about 27 Gbit/s on average.
Part 2 · API and data model
The upload API
Uploading a photo is a three-step conversation, not one request. The phone first tells the API what it wants to send. The API creates a photo record in the pending state and returns a signed upload URL, an address that lets the phone send the bytes directly to the object store for a short time. The phone sends the bytes. Then the phone tells the API it is done.
POST /v1/photos HTTP/1.1 Content-Type: application/json {"caption": "Marine Drive at dusk", "content_type": "image/jpeg", "bytes": 4450697}
Step 1: ask for an upload slot.
{
"photo_id": "289910292480005120",
"upload_url": "https://uploads.example.com/u/7/2899...
"expires_in": 300
}The reply, with the signed URL shortened.
POST /v1/photos/289910292480005120/complete HTTP/1.1
Step 3: the bytes are in the store, please process them.
The id is a string in JSON because a 64-bit number can lose digits in some clients, for example in JavaScript numbers. The caller sends the byte count and type up front so the API can put them into the signature and refuse anything larger or of another type, which the fourth lesson shows. Step 3 returns at once with 202 Accepted, because the processing runs in the background.
| Call | What it does | Notes |
|---|---|---|
POST /v1/photos | Create a pending photo and return a signed URL | Rate limited; the caption is checked now |
POST /v1/photos/{id}/complete | Mark the upload finished and start processing | Safe to repeat |
GET /v1/photos/{id} | Status and the list of sizes | Public once the status is ready |
GET /v1/users/{id}/photos | A user's photos, newest first |
Tables and the life of a photo
The metadata is small and structured, so it lives in a database; the bytes live in the object store. photo has one row per photo. Its status column moves through a short life: pending when the slot is created, uploaded when the API has checked the bytes, ready when the sizes exist, and rejected if the file is not a usable image. rendition has one row per size, so the client can choose a size that fits its screen. follow, like and comment are the social tables.
import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE photo ( id INTEGER PRIMARY KEY, -- 64-bit id, see lesson 5 owner INTEGER NOT NULL, caption TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','uploaded','ready','rejected')), object_key TEXT NOT NULL, -- where the original lives created_at INTEGER NOT NULL); CREATE TABLE rendition ( photo_id INTEGER NOT NULL REFERENCES photo(id), name TEXT NOT NULL, -- '1080', '640', '320', 'thumb' width INTEGER NOT NULL, height INTEGER NOT NULL, bytes INTEGER NOT NULL, PRIMARY KEY (photo_id, name)); CREATE TABLE follow ( follower INTEGER NOT NULL, author INTEGER NOT NULL, PRIMARY KEY (follower, author)); CREATE INDEX photo_by_owner ON photo (owner, id DESC); CREATE TABLE like ( photo_id INTEGER NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (photo_id, user_id)); CREATE TABLE comment ( id INTEGER PRIMARY KEY, photo_id INTEGER NOT NULL, user_id INTEGER NOT NULL, body TEXT NOT NULL); """)
Python 3.12.10 with sqlite3. Save this and the next block as photo_schema.py.
db.execute("INSERT INTO photo (id, owner, object_key, created_at)" " VALUES (1, 7, 'u/7/1/original', 1000)") print(db.execute("SELECT id, status FROM photo").fetchall()) db.execute("UPDATE photo SET status = 'uploaded' WHERE id = 1") try: db.execute("UPDATE photo SET status = 'published' WHERE id = 1") except sqlite3.IntegrityError as e: print("rejected:", e.args[0].split(":")[0]) print([r[1] for r in db.execute("PRAGMA table_info(photo)")])
Continue in the same file: a new photo, then a state that does not exist.
[(1, 'pending')] rejected: CHECK constraint failed ['id', 'owner', 'caption', 'status', 'object_key', 'created_at']
Output of the script.
The CHECK constraint turns the list of states into something the database enforces. A bug that tries to set the status to published fails loudly, as the run shows, and does not leave a row in a state no code understands. The primary key on like is (photo_id, user_id), which makes a second like from the same person impossible at the database level; the sixth lesson relies on that.
Part 3 · High-level design with direct uploads
The pieces
The design has six parts. The Photo API handles the three calls from the previous lesson and owns the metadata database. The object store holds the bytes. A job queue carries one message per finished upload. Resize workers read the queue, fetch the original, write the smaller sizes and update the status. The CDN serves the sizes to viewers. The feed service, the fifth lesson, builds the follow feed from the metadata.
The important choice is the direct upload. In the simple design the phone would send the photo to an application server, which would pass it on to storage. Every byte would cross two networks and occupy a server for as long as a slow phone takes to send it. With a signed URL, the phone talks to the object store itself. The API handles three small requests, and the large transfer is the object store's work, which it was built for.
The queue is the second choice. Resizing takes time, and a spike of uploads must not slow down the API or lose photos. The message queue chapter showed how a queue absorbs a spike and lets workers drain it. Here the job message holds only the photo id; the worker finds the key in the database.
Watch for the photo bytes skipping the API servers
Read it as steps
Why each part is separate
Each part scales on its own load. API servers scale with request count and are stateless. The object store scales with bytes. Workers scale with the queue's depth: if the queue grows, add workers. The CDN scales with viewers. If everything ran in one server, the slowest resource would set the size of every other.
The queue also makes the pipeline safe to repeat. A worker acknowledges a job only after the sizes are written. If it crashes, the queue redelivers the job, as the message queue chapter described for at-least-once delivery. This is safe because the output keys are fixed, for example u/7/{photo_id}/640. A second run writes the same bytes to the same key, so processing is idempotent, as the core concepts chapter defined it: doing it twice is the same as doing it once.
| Part | State it holds | If it fails |
|---|---|---|
| Photo API | None | Other copies take over behind the load balancer |
| Metadata database | Photos, follows, likes | Replica takes over; uploads pause briefly |
| Object store | All the bytes | Replicated or erasure coded; a lost node is repaired |
| Job queue | Pending jobs | Durable; jobs wait and are redelivered |
| Resize workers | None | Other workers take the job after the timeout |
| CDN | Cached sizes | Requests fall through to the store |
A photo is not visible to others until its status is ready. Until then the owner sees the original, or a local preview in the app, so the first seconds feel instant even though the sizes are still being made. The API never says a photo is posted until the original is safely stored, which is how the durability requirement is met.
Part 4 · Deep dive: signed upload URLs and processing
Signing an upload
The blob store chapter showed how a signed URL carries its own permission, with an HMAC over the things it allows. For downloads it signed the method, the path and the expiry; for uploads we sign more fields: the method, the key, the content type, the largest size allowed and the expiry.
Amazon S3 documents the same idea. Its guide says a presigned URL can be used to upload a specific object, that the URL can be used many times until it expires, and that S3 replaces an existing object with the same key. It also calls these URLs bearer tokens: whoever holds one can use it. With the SDKs a URL can live up to 7 days, and it stops working earlier if the credentials that signed it expire; ours lives five minutes. Our code shows the first two behaviours in its output below, and the line STORE[key] = body in the server is the third. The page does not describe a size or content-type limit for a presigned upload, so the max and ct fields in our URL are our own scheme, not a description of S3. The first block signs the URL.
import hashlib, hmac, time from urllib.parse import parse_qs, urlencode, urlsplit SECRET = b"demo-secret-kept-on-the-api-server" def _mac(key, ctype, max_bytes, exp): msg = f"PUT\n{key}\n{ctype}\n{max_bytes}\n{exp}".encode() return hmac.new(SECRET, msg, hashlib.sha256).hexdigest() def sign_put(key, ctype, max_bytes, ttl, now=None): """Path and query that allow one PUT of this key, type and size.""" exp = int((time.time() if now is None else now) + ttl) q = urlencode({"ct": ctype, "max": max_bytes, "exp": exp, "sig": _mac(key, ctype, max_bytes, exp)}) return f"/{key}?{q}"
Python 3.12.10, standard library. Save these two blocks as signing.py.
def check_put(path, ctype, length, now=None): """Return (http status, reason); (200, 'ok') when allowed.""" u = urlsplit(path) q = {k: v[0] for k, v in parse_qs(u.query).items()} key = u.path.lstrip("/") try: exp, mx = int(q["exp"]), int(q["max"]) good = _mac(key, q["ct"], mx, exp) except (KeyError, ValueError): return 403, "malformed URL" if not hmac.compare_digest(good, q.get("sig", "")): return 403, "bad signature" if (time.time() if now is None else now) > exp: return 403, "expired" if ctype != q["ct"]: return 415, "content type not allowed" if length > mx: return 413, "too large" return 200, "ok"
Continue in signing.py: the checks, cheapest first.
A store and a client
import sys from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from signing import check_put STORE = {} # key -> bytes; a real store uses disks class Handler(BaseHTTPRequestHandler): def do_PUT(self): length = int(self.headers.get("Content-Length", 0)) ctype = self.headers.get("Content-Type", "") body = self.rfile.read(length) # always drain the request status, reason = check_put(self.path, ctype, length) if status == 200: key = self.path.split("?")[0].lstrip("/") STORE[key] = body # replaces any old copy self.send_response(status) self.send_header("Content-Length", str(len(reason))) self.end_headers() self.wfile.write(reason.encode())
Save these two blocks as server.py. Run it with: python server.py 55522
def do_GET(self): # internal read, unsigned body = STORE.get(self.path.lstrip("/")) self.send_response(200 if body is not None else 404) self.send_header("Content-Length", str(len(body or b""))) self.end_headers() self.wfile.write(body or b"") def log_message(self, *args): pass port = int(sys.argv[1]) ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
Continue in server.py.
from PIL import Image # A 4000 x 3000 test picture: a gradient with film-grain noise. w, h = 4000, 3000 base = Image.linear_gradient("L").resize((w, h)).convert("RGB") grain = Image.effect_noise((w, h), 30).convert("RGB") Image.blend(base, grain, 0.35).save("test.jpg", quality=90) print("wrote test.jpg")
Save as make_image.py and run: uv run --with pillow==13.0.0 make_image.py
import sys, time, urllib.error, urllib.request from signing import sign_put BASE = sys.argv[1] data = open("test.jpg", "rb").read() print(f"test.jpg is {len(data):,} bytes") def put(path, body, ctype): req = urllib.request.Request(BASE + path, data=body, method="PUT", headers={"Content-Type": ctype}) try: with urllib.request.urlopen(req) as r: return r.status, r.read().decode() except urllib.error.HTTPError as e: return e.code, e.read().decode() key = "u/7/1001/original" good = sign_put(key, "image/jpeg", 5_000_000, ttl=300) print("valid URL ", put(good, data, "image/jpeg")) print("same URL again ", put(good, data, "image/jpeg")) print("other key ", put(good.replace("1001", "1002"), data, "image/jpeg")) old = sign_put(key, "image/jpeg", 5_000_000, ttl=60, now=time.time() - 120) print("expired URL ", put(old, data, "image/jpeg")) print("wrong type ", put(good, data, "text/html")) small = sign_put("u/7/1003/original", "image/jpeg", 1000, ttl=300) print("body over max ", put(small, data, "image/jpeg"))
Save as client.py. Run: python client.py http://127.0.0.1:55522
Checking the upload
The photo is stored, but the API does not trust it yet. In the complete call the API looks at what arrived. It confirms the object exists, that its size is within the limit and that it is a real image, not a different file with an image name. The worker repeats the image check when it decodes the file. A file that fails becomes rejected and is deleted.
Watch for the API never touching the photo bytes
Read it as steps
Create a slot, upload with the signed URL, complete, and let a worker finish the job.
The sequence matches the status column from the second lesson: pending, then uploaded, then ready. At every step one party is responsible, and the next step starts only when the previous one has been recorded. A crash between two steps leaves the photo in a known state that the cleanup in the sixth lesson can find.
Making the sizes
The worker decodes the original with Pillow, the Python imaging library, version 13.0.0 here, and makes four smaller JPEGs. The script below produces them in memory and prints their sizes; a real worker would then write each one to its fixed key. Three details matter. Image.verify() checks the file's structure and fails for a file that is not really an image; Pillow's documentation says the file must be reopened to load the image afterwards, so the code opens it a second time. ImageOps.exif_transpose applies the camera's rotation flag, so that a photo taken in portrait is not stored sideways. And thumbnail shrinks the image in place to fit inside a square, keeping the proportions and never enlarging.
import io, sys, urllib.request from PIL import Image, ImageOps BASE, key = sys.argv[1], sys.argv[2] data = urllib.request.urlopen(f"{BASE}/{key}").read() Image.open(io.BytesIO(data)).verify() # fails if not an image im = Image.open(io.BytesIO(data)) # verify() spends it: reopen print("original:", im.format, im.size, f"{len(data):,} bytes") im = ImageOps.exif_transpose(im).convert("RGB") for name, edge in (("1080", 1080), ("640", 640), ("320", 320), ("thumb", 150)): copy = im.copy() copy.thumbnail((edge, edge)) # keeps aspect, never enlarges out = io.BytesIO() copy.save(out, "JPEG", quality=80) print(f"{name:>6}: {copy.size[0]}x{copy.size[1]}" f" {out.tell():>8,} bytes")
Save as worker.py. Run: uv run --with pillow==13.0.0 worker.py BASE KEY
original: JPEG (4000, 3000) 4,450,697 bytes 1080: 1080x810 60,097 bytes 640: 640x480 13,869 bytes 320: 320x240 3,306 bytes thumb: 150x113 1,499 bytes
Output for the uploaded test picture, 4000 by 3000 pixels.
The 4,450,697-byte original became 60,097, 13,869, 3,306 and 1,499 bytes. These sizes come from a synthetic test picture, a gradient with noise. A real photograph compresses less, so the numbers do not replace the estimates from the first lesson, which are assumptions. What the run does show is the mechanism and that the aspect ratio is kept: 4000 by 3000 becomes 1080 by 810.
Bombs and metadata
Two safety points close the pipeline. Pillow protects against decompression bombs, small files that expand to enormous images. It warns when an image has more pixels than Image.MAX_IMAGE_PIXELS and raises an error above twice that. The default limit is 89,478,485 pixels. The next script lowers the limit to try both cases on a 400 by 300 image, which has 1,20,000 pixels. And the worker should write its output without the metadata of the original, since photos often carry camera details and GPS coordinates.
import io, warnings from PIL import Image buf = io.BytesIO() Image.new("RGB", (400, 300), "navy").save(buf, "PNG") # 120,000 pixels data = buf.getvalue() print("default limit:", f"{Image.MAX_IMAGE_PIXELS:,}") for limit in (100_000, 50_000): Image.MAX_IMAGE_PIXELS = limit with warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") try: Image.open(io.BytesIO(data)) print(f"limit {limit:>7,}: opened,", [w.category.__name__ for w in caught]) except Exception as e: print(f"limit {limit:>7,}: {type(e).__name__}") print(" ", str(e).split(",")[0])
Save as bomb.py and run: uv run --with pillow==13.0.0 bomb.py
default limit: 89,478,485 limit 100,000: opened, ['DecompressionBombWarning'] limit 50,000: DecompressionBombError Image size (120000 pixels) exceeds limit of 100000 pixels
Output. The error names twice the limit, 100000 pixels.
At a limit of 1,00,000 pixels the image has more pixels than the limit but fewer than twice the limit, so it opens with a DecompressionBombWarning. At 50,000 it has more than twice the limit and is refused with DecompressionBombError. A worker for strangers' files should treat both as a rejection.
import io from PIL import Image, ImageOps im = Image.new("RGB", (800, 600), "teal") exif = Image.Exif() exif[0x010F] = "ExampleCam" # Make exif[0x0112] = 6 # Orientation: rotate 90 exif.get_ifd(0x8825)[1] = "N" # GPS latitude reference buf = io.BytesIO() im.save(buf, "JPEG", exif=exif) src = Image.open(io.BytesIO(buf.getvalue())) print("upload has exif:", len(src.getexif()) > 0, dict(src.getexif())) print("upload has gps ifd:", dict(src.getexif().get_ifd(0x8825))) fixed = ImageOps.exif_transpose(src).convert("RGB") fixed.thumbnail((300, 300)) out = io.BytesIO() fixed.save(out, "JPEG", quality=80) res = Image.open(io.BytesIO(out.getvalue())) print("size after rotate+thumbnail:", res.size) print("output exif entries:", len(res.getexif())) print("output gps ifd:", dict(res.getexif().get_ifd(0x8825)))
Save as exif_test.py. A picture with a rotation flag and a GPS tag.
Part 5 · Deep dive: sharded ids and the follow feed
An id that says where the photo lives
The metadata for crores of new photos a day, with every follow, like and comment, outgrows one database in time, so the photo table is split across shards, and each shard is a database on its own server. Which shard holds a photo? The usual answer is a lookup table, which is one more thing to build, store and keep fast. The alternative is to put the answer into the id, so that anyone holding an id knows its shard with no lookup.
The sequencer chapter built Snowflake-style ids from a timestamp, a machine number and a sequence. We reuse that idea with a different split: 41 bits of milliseconds since our own epoch, 12 bits for the logical shard, and 10 bits for a sequence within one shard and one millisecond. That is 63 bits, so the top bit of a 64-bit integer stays zero and the id fits a signed integer, which is what most databases and some languages use. (With 41 bits of time, a 13-bit shard field would use all 64 bits and the id would turn negative after about 35 years.) Twelve bits give 4,096 logical shards. Each logical shard has one generator, run by whichever server currently hosts it, so two servers never issue ids with the same shard bits at the same time. They are mapped to a smaller number of physical servers, so we can later move a logical shard to another server without changing any id. This layout is our design, in the style the earlier chapter described, and not a claim about any company's ids.
import time EPOCH_MS = 1_735_689_600_000 # our own epoch: 1 Jan 2025 UTC SHARD_BITS, SEQ_BITS = 12, 10 # 41 + 12 + 10 = 63 bits, sign bit 0 class PhotoIds: """One generator per logical shard; the clock is injectable.""" def __init__(self, shard, clock=lambda: int(time.time() * 1000)): assert 0 <= shard < 1 << SHARD_BITS self.shard, self.clock = shard, clock self.last_ms, self.seq = -1, 0 def next(self): ms = self.clock() - EPOCH_MS if ms == self.last_ms: self.seq = (self.seq + 1) & ((1 << SEQ_BITS) - 1) if self.seq == 0: # 1,024 used: wait while ms <= self.last_ms: ms = self.clock() - EPOCH_MS else: self.seq = 0 self.last_ms = ms stamp = ms << (SHARD_BITS + SEQ_BITS) return stamp | (self.shard << SEQ_BITS) | self.seq def decode(photo_id): seq = photo_id & ((1 << SEQ_BITS) - 1) shard = (photo_id >> SEQ_BITS) & ((1 << SHARD_BITS) - 1) ms = photo_id >> (SHARD_BITS + SEQ_BITS) return ms + EPOCH_MS, shard, seq
Python 3.12.10. Save this and the next two blocks together as photo_ids.py.
Decoding and routing an id
fixed = lambda: EPOCH_MS + 86_400_000 * 400 # a frozen clock a, b = PhotoIds(shard=5, clock=fixed), PhotoIds(shard=4000, clock=fixed) ids = [a.next(), a.next(), b.next()] for i in ids: ts, shard, seq = decode(i) print(f"{i:>20} ms+{ts - EPOCH_MS} shard {shard:>4} seq {seq}") SERVERS = 4 def route(photo_id): return decode(photo_id)[1] * SERVERS // (1 << SHARD_BITS) print("servers:", [route(i) for i in ids]) years = (1 << 41) / (1000 * 86_400 * 365.25) print(f"41 bits of milliseconds last {years:.1f} years") print(f"ids per shard per millisecond: {1 << SEQ_BITS:,}") biggest = (1 << (41 + SHARD_BITS + SEQ_BITS)) - 1 # all fields ones print("largest possible id fits a signed 64-bit integer:", biggest < 1 << 63) live = PhotoIds(shard=1) batch = [live.next() for _ in range(5000)] print("5,000 ids from a live clock, all unique and rising:", len(set(batch)) == 5000 and batch == sorted(batch))
Continue in the same file: make, decode and route ids.
decode reverses the shifts, and route maps the logical shard to one of four servers by dividing the 4,096 shards into four ranges. The last four lines check the arithmetic. 41 bits of milliseconds last 69.7 years, each shard can issue 1,024 ids in a millisecond, and the largest id the layout can make still fits a signed 64-bit integer. The final test draws 5,000 ids from the live clock for one shard, which is more than 1,024 in a millisecond, so it forces the wait at least once. All the ids were unique and in order.
144955146240005120 ms+34560000000 shard 5 seq 0 144955146240005121 ms+34560000000 shard 5 seq 1 144955146244096000 ms+34560000000 shard 4000 seq 0 servers: [0, 0, 3] 41 bits of milliseconds last 69.7 years ids per shard per millisecond: 1,024 largest possible id fits a signed 64-bit integer: True 5,000 ids from a live clock, all unique and rising: True
Output of the first two blocks.
The three printed ids show the layout at work. The first two share a shard (5) and a millisecond and differ only in the sequence, 0 and 1. The third is from shard 4000, and route sends it to server 3 while the other two go to server 0. The id told us that without asking a directory.
The follow feed
The follow feed is the list of the newest photos from the accounts you follow. A photo gets its shard bits from its owner's logical shard and is stored there, so one owner's photos are one shard's query. To build a feed, group the followed accounts by shard, ask each shard for its newest photos for those accounts, and merge the answers. That is the scatter-gather pattern from the search chapter, with a cheap merge. Because ids sort by time, the merge is a plain merge of sorted lists, and the id itself is the cursor: the next page is the photos with an id lower than the last one shown.
import heapq # Photos from three shards, uploaded two milliseconds apart. now = [EPOCH_MS + 5_000] gens = {s: PhotoIds(s, clock=lambda: now[0]) for s in (5, 2000, 4000)} by_shard = {s: [] for s in gens} for s in (5, 2000, 4000, 5, 2000, 5): now[0] += 2 by_shard[s].append(gens[s].next()) for s in by_shard: by_shard[s].reverse() # newest first def follow_feed(lists, size, before=None): """Merge newest-first lists; the id itself is the cursor.""" merged = heapq.merge(*lists.values(), reverse=True) return [i for i in merged if before is None or i < before][:size] page1 = follow_feed(by_shard, 3) page2 = follow_feed(by_shard, 3, before=page1[-1]) for page in (page1, page2): print([(decode(i)[0] - EPOCH_MS - 5_000, decode(i)[1]) for i in page]) print("no photo twice:", not set(page1) & set(page2)) print("all six shown: ", len(page1 + page2) == 6)
Continue in the same file: merge photos from three shards.
[(12, 5), (10, 2000), (8, 5)] [(6, 4000), (4, 2000), (2, 5)] no photo twice: True all six shown: True
Output of the last block.
Six photos from shards 5, 2000 and 4000 were made two milliseconds apart. Page one holds the newest three, from milliseconds 12, 10 and 8, taken from shards 5, 2000 and 5. Page two holds 6, 4 and 2. No photo appeared twice and all six were shown. The cursor is a single number, with no score, because time order is the order. That is simpler than the feed of the previous chapter, which paid for a stored list to support a ranked order.
The design has costs. A feed for someone who follows many accounts touches many shards, so the slowest shard sets the latency, the tail problem from the non-functional chapter. The usual remedies are a stored feed per user for most people and a merge at read time for accounts with a huge number of followers, as in the microblog chapter. Ids that contain a time also reveal when a photo was created, which is fine for public photos and a reason to think before using them for private data.
Part 6 · Likes, comments, CDN delivery and failures
Likes and comments
A like is a small write with a large audience. Three rules keep it correct. First, the table has a primary key of photo and user, so a person can like a photo only once; a double tap or a retry is absorbed by the database. Second, the write is idempotent: liking an already liked photo changes nothing. Third, the counter is adjusted only when the row really changed. The script below applies these rules with SQLite.
import sqlite3 db = sqlite3.connect(":memory:") db.executescript(""" CREATE TABLE photo (id INTEGER PRIMARY KEY, like_count INTEGER NOT NULL DEFAULT 0, status TEXT NOT NULL, object_key TEXT, created_at INTEGER NOT NULL); CREATE TABLE like (photo_id INTEGER NOT NULL, user_id INTEGER NOT NULL, PRIMARY KEY (photo_id, user_id)); INSERT INTO photo (id, status, object_key, created_at) VALUES (1, 'ready', 'u/7/1/original', 0), (2, 'pending', 'u/7/2/original', 100), (3, 'pending', 'u/8/3/original', 9000); """) def set_like(photo_id, user_id, on): if on: cur = db.execute("INSERT OR IGNORE INTO like VALUES (?, ?)", (photo_id, user_id)) delta = cur.rowcount # 1 when new, 0 for a repeat tap else: cur = db.execute("DELETE FROM like WHERE photo_id = ? AND" " user_id = ?", (photo_id, user_id)) delta = -cur.rowcount db.execute("UPDATE photo SET like_count = like_count + ?" " WHERE id = ?", (delta, photo_id))
Python 3.12.10. Save this and the next block as likes.py.
set_like uses INSERT OR IGNORE, which inserts nothing if the key exists, and reads rowcount to learn whether a row was added. That one number, 1 or 0, is the change to the counter. Removing a like works the same way in reverse. Both the row change and the counter update happen in one transaction, as the databases chapter described, so they cannot disagree.
def count(photo_id): row = db.execute("SELECT like_count FROM photo WHERE id = ?", (photo_id,)).fetchone() return row[0] for on in (True, True, True): # one user taps three times set_like(1, 42, on) set_like(1, 43, True) print("likes after 3 taps and one other user:", count(1)) set_like(1, 42, False) set_like(1, 42, False) # a repeated unlike print("after two unlikes by the same user:", count(1)) # Sweep uploads that never completed within an hour. now = 9100 swept = db.execute("DELETE FROM photo WHERE status = 'pending'" " AND created_at < ? RETURNING id, object_key", (now - 3600,)).fetchall() print("swept:", swept) print("left:", db.execute("SELECT id, status FROM photo" " ORDER BY id").fetchall())
Continue in the same file: repeated taps, then a cleanup.
Delivery, cleanup and failures
Delivery is the CDN's job. Each rendition has a fixed URL that contains the photo id and the size, for example /p/{id}/640.jpg. The image for a given id and size never changes, so it can carry a long max-age, as the cdn chapter explained for versioned files. A deleted photo is the exception. The API marks it deleted at once, so no feed or page lists it, and then asks the CDN to purge its URLs. Until the purge reaches every edge, someone with the direct address could still see it, which is a limit to state honestly.
The run's second half shows a cleanup that every upload flow needs. Phones lose signal and apps are closed, so some uploads never complete. A job sweeps pending photos older than an hour, deletes them and returns their keys so the objects can be deleted from the store. In the run, photo 2 was pending and old, so it was swept; photo 3 was pending but recent, so it stayed; photo 1 was ready and untouched.
Failures and extensions
| Failure | What happens | What we do |
|---|---|---|
| Phone loses signal mid-upload | A pending photo and maybe a partial object | Retry with the same URL until it expires; sweep after an hour |
| Worker crashes | The job is redelivered | Idempotent output keys make the repeat safe |
| Bad image file | Decoding fails | Mark rejected; delete the object |
| Queue grows long | Sizes appear late | Add workers; show the original meanwhile |
| Metadata shard down | Photos on it cannot be listed | Replica promoted; other shards unaffected |
| CDN edge down | Requests fall to another edge | Fall back to the store |
Extensions follow from the same parts. Private accounts need an access check in the API and signed read URLs with short lifetimes, so the CDN cannot hand a private photo to strangers. Video adds a longer processing pipeline, the subject of the video platform chapter. Content checks add a worker stage before ready that scans for banned material. Each is another stage on the queue, not a redesign.
To watch the system, measure the upload success rate, the age of the oldest queued job, the share of photos stuck in pending or uploaded for more than a few minutes, and the cache hit ratio at the edge. The queue age is the first number to move when workers fall behind.