AlgoViz

Design an image hosting service (like Imgur)

medium 50 min

Upload a picture, get a link at once, and let the whole world look at it.

API and data

The contract first, then the data that serves it.

Entities

Name the things first

Image (ID, owner or none, status, hash, sizes), Blob (hash, place, references), Album (ordered images), Upload (offset, expiry) and View event. Status is uploading, processing, ready, review, blocked or deleted.

API

Endpoints and addresses

HTTP
POST /v1/uploads                           Idempotency-Key: 9f2...{ "bytes": 2400000, "type": "image/jpeg" }→ 201 { "upload_id": "u-81", "put_url": "https://...signed...",        "expires_in": 900 }PUT <put_url>                              file goes to the private storePOST /v1/uploads/u-81/complete{ "title": "Harbour", "album": null }→ 201 { "id": "k3Pz9Qa", "link": "https://img.example/k3Pz9Qa",        "delete_token": "shown once", "status": "processing" }GET /v1/images/k3Pz9Qa                     record, sizes, statusDELETE /v1/images/k3Pz9Qa                  owner, or Delete-Token header→ 204POST /v1/albums   { "ids": ["k3Pz9Qa", "b71XcDe"], "title": "Trip",                    "privacy": "public|hidden|secret", "cover": "k3Pz9Qa" }PUT  /v1/albums/{id}/images  { "add": ["p0LmN2x"] }GET  /v1/albums/{id}         images in orderGET  /v1/gallery/hot?cursor=...            trendingGET https://img.example/k3Pz9Qa_m.webp     a finished copy→ 200  Cache-Control: public, max-age=3600, s-maxage=2592000
Files use their own host, img.example, with no cookies. Calls use api.example.

Sizes by suffix

SuffixLongest sideShapeMadeUse
_s160keeps shapeaheadLists, small previews
_m640keeps shapeaheadPhones, forum posts
_l1,280keeps shapeaheadFull page
_q160square, croppedon demandGrids, avatars
_x2,048keeps shapeon demandLarge screens
Each size has its own address, so it is its own cache entry. Any other suffix is 404.

Status codes

CodeMeaning here
201Upload opened or completed
200 placeholderNot ready: short cache, 5 s
404Unknown, deleted, or wrong token
409Same idempotency key, other content
413Over 20 MB
415Not an accepted image
429Limit reached, with Retry-After
451Removed for a legal reason

API decisions

  1. Interviewer

    Why does the file not pass through your API?

  2. You

    The API would only copy bytes. It gives a signed address that allows one key, one size limit and 15 minutes. The client sends the file to storage, then says complete.

    • Large or shaky uploads use a resumable protocol: ask for the offset, go on from there.
    • The complete call is idempotent and checks size and type of what arrived.
    • Files without a complete call are removed after 24 hours.
  3. Interviewer

    How can an anonymous person delete?

  4. You

    A random delete token of 128 bits, shown once. We store only its hash and compare in constant time. It travels in a header, because addresses end up in logs.

  5. Interviewer

    And limits?

  6. You

    Per address for anonymous clients, for example 50 uploads an hour; per account, 1,250 a day; per application key as well. The strictest wins. Details are in API rate limiter. Shared addresses are common, so a limit leads to a sign-in prompt and not to a ban.

Database

Data model

SQL
CREATE TABLE images (  id            varchar(10) PRIMARY KEY,   -- random base62  user_id       uuid,                      -- null when anonymous  token_hash    bytea NOT NULL,  content_hash  bytea,                     -- SHA-256, set by the worker  status        text NOT NULL,  mime_type     text NOT NULL,  bytes         bigint NOT NULL,  width int, height int,  title         varchar(256),  mature        boolean NOT NULL DEFAULT false,  created_at    timestamptz NOT NULL DEFAULT now(),  deleted_at    timestamptz);CREATE TABLE user_images (                 -- its own shards, by user  user_id uuid, created_at timestamptz, image_id varchar(10),  PRIMARY KEY (user_id, created_at, image_id));CREATE TABLE blob_refs (                   -- shards by hash  content_hash bytea, image_id varchar(10),  PRIMARY KEY (content_hash, image_id));CREATE TABLE albums (  id varchar(10) PRIMARY KEY, user_id uuid, token_hash bytea NOT NULL,  title varchar(256), privacy text NOT NULL, cover_id varchar(10));CREATE TABLE album_images (  album_id varchar(10), position int, image_id varchar(10) NOT NULL,  PRIMARY KEY (album_id, position));
Names of duplicate pictures differ; their bytes are one blob. Counts live elsewhere.

What lives where

DataStoreWhy
Images, albums, usersPostgreSQL, sharded by IDTransactions, known lookups
FilesObject storageSize, durability, price
Sessions, limits, hot recordsRedisShort life, atomic counters
Titles and tagsSearch indexText queries, rebuilt from records
Views, trafficColumn store such as ClickHouseSums over many rows
JobsQueueRetry, spread work

Album rows of one album share a shard. Their images may live on others, so a foreign key across shards is not possible: the album reader skips images that are gone. Write order on complete: blob stored, then record processing, then job. A sweeper finds records with no job after a minute, or use an outbox.