A conference wants speakers to upload slide decks and attendees to search published files. The upload API must handle large objects, the search page needs fast lookups, and a flood of new uploads must stay within the scanner's capacity. A relational database could store small files and perform basic search. As the product grows, you need to know what changes when you move bytes, search, and admission into specialized components.
By the end, you can choose which system owns which fact, design an idempotent upload and publication path, work an inverted-index query and token bucket by hand, and diagnose how object storage, search lag, and rate limits can fail independently. You will reuse the durable events and consumer semantics from Queues, Workers, and Backpressure.
Split the byte path from the catalog#
An object store typically exposes buckets, object keys, bytes, and metadata through an API. Think “fetch this object” or “write this object version.” A filesystem usually exposes directory and file operations, including semantics specific to files and mounts. A relational database gives you records, constraints, transactions, and query plans. The right choice depends on what the workload does most often.
For a small catalog, database metadata and basic full-text search may be enough. An object store becomes attractive when you need large transfers, multipart uploads, independent lifecycle policies, or delivery through a CDN. Keep relational metadata for ownership, publication, version, and visibility. Give each new object version a stable storage key. A path prefix can help organize objects, but a key naming convention does not define access permissions by itself.
| Layer | Owns | Typical operation |
|---|---|---|
| Catalog database | Owner, publication status, visibility, and current version | Decide whether a given caller can access a published deck |
| Object storage | Bytes and object-level integrity metadata | Upload or retrieve a specific version |
| Search index | Rebuildable candidate projection | Find published decks matching selected words |
| Admission policy | Scope, rate, burst, quota, and fail behavior | Permit or reject new protected work |
S3 is one concrete example. It documents strong read-after-write consistency for successful PUT and DELETE operations and associated reads, and atomic updates to one object key. That guarantee does not cover your catalog row, the search index, a CDN copy, or a different storage provider. Use a versioned key or conditional writes where replacing the same object could race.
Design an upload with explicit publication#
- Reserve an upload. Authenticate the caller, check object size and quota, and create an upload record tied to one owner and object key. Repeated reservation attempts with the same client identity and intent should return the existing record.
- Authorize the byte transfer. Give the client a short-lived, scoped signed URL or equivalent upload credential. A signed URL is a bearer capability. Protect it from logs and use a private destination. For large files, upload parts independently and finish the upload using the provider's completion API.
- Confirm the result. The client or a storage event notifies the API. Verify that the expected object version exists with permitted byte length and integrity checks. An S3 multipart ETag is not generally a hash of the complete object. Use a supported checksum when you need to verify bytes.
- Validate and publish. Scan or validate the object in an isolated worker with explicit cost and size bounds. Then atomically mark the catalog entry published and write an outbox event in the catalog transaction. Index only the published version. Check authorization against the catalog when issuing a signed download.
- Reconcile incomplete states. Expire abandoned upload reservations, abort incomplete multipart uploads, and sweep uploaded objects that never reached a valid publication state. Respect retention and legal holds. Make version replacement and cleanup conditional so a delayed worker cannot delete a newly accepted object.
Diagram key and text version
- Entry
- Process
- Data
- Outcome
- Private object → Validate file: upload complete
- Validate file → Catalog + outbox: checks pass
- Catalog + outbox → Search index: publish event
A timeout while completing an upload is an ambiguous outcome. The client may retry completion after the object already exists. Look up the reserved object and its version, and apply allowed status transitions. A storage notification can trigger verification before the catalog authorizes publication. Pin publication and downloads to the exact version the worker validated. If the upload credential is reusable until expiry, a later write to the same key must leave that published version intact. If a reservation expires before an event arrives, treat the object according to your reconciliation policy. A version-specific download URL helps keep CDN copies and catalog state aligned. When access is revoked, a previously issued signed URL or cached response may remain usable within its policy. Budget the revocation window explicitly.
Estimate data volume and transfer
At 500 uploads per day and 20 MiB per upload, new bytes total 10,000 MiB per day, about 9.77 GiB. Thirty days at that rate retain about 293 GiB for one version per upload, ignoring overhead, replication, and deletions within the interval. If each deck is downloaded ten times and the CDN serves eight of those ten requests without contacting object storage, the daily object-store download estimate is 500(2)(20)=20{,}000 MiB, about 19.5 GiB. Both numbers are planning estimates. Track retained versions, incomplete multipart bytes, scan copies, request costs, and egress separately. A cap on requests alone does not protect bandwidth if object sizes vary significantly.
Build a search index by hand#
An inverted index maps a normalized term to a list of matching document IDs called a posting list. An analyzer tokenizes and normalizes text. Production analyzers may also record positions, normalize language-specific forms, or add synonyms. Apply compatible analysis at query time so terms in a query can match their indexed representation.
For this example, use lowercase word tokens and ignore ordering within a title.
| ID | Slide deck title |
|---|---|
| A | Intro storage design |
| B | Storage systems |
| C | Search design |
The posting list for storage is [A, B], and for design it is [A, C]. An AND query for “storage design” intersects the lists and returns A. An OR query takes their union. Exact phrase queries need term positions. In sorted posting lists, a two-pointer intersection advances the pointer whose document ID sorts earlier, collects equal IDs, and stops when either list ends. The small lab uses sets to demonstrate the result. Ranking may also use term frequencies, rarity, field weights, recency, or product signals. Ranking and access filtering solve separate problems.
Search sees a projection. After accepting a metadata write, a worker may still need to publish, transform, and index it. A search engine such as Elasticsearch has a refresh step that makes recent changes searchable. Visibility at refresh and durability on disk are separate concerns. Prefer an explicit “processing” or “publishing” status and measure time from catalog commit to searchable result. Forcing a refresh for every small write can harm throughput.
Make search rebuildable and safe across reordering
Include an object ID and a monotonic catalog revision in each event. Apply a newer revision once. If workers see revision 5 before revision 4, ignore 4 because a newer snapshot supersedes it. A delete needs a versioned tombstone or equivalent durable record, so a delayed update cannot recreate what was deleted. A delta such as “append a tag” cannot necessarily skip earlier deltas. Use full projections, an ordered stream, or reconcile missing changes against authority.
To rebuild, take an authoritative snapshot with a known change-log boundary, build a new index, and replay changes from that boundary. Compare both indexes on representative searches and check version coverage before switching traffic. If history disappears before the rebuild catches up, take a new consistent snapshot. Keep the old index available for bounded rollback, while applying privacy and deletion policies to both indexes and backups.
Store as little sensitive data as possible in the projection. Enforce tenant and visibility filters in search to prevent cross-tenant results. For an item whose permissions may have changed, recheck authority before returning sensitive metadata or granting access. A stale index can leak information even if the signed download remains blocked. Keep indexing and access enforcement separate, and measure time from revocation to removal from every customer-visible view.
Protect the expensive path with explicit budgets#
A rate limit caps the pace of work for a given identity and operation. A quota often caps usage over a longer horizon, such as bytes stored or uploads per month. A concurrency limit caps units running at the same time. They complement one another. A caller may be below its monthly byte quota but still overwhelm the scanner with one burst of expensive files.
Choose the key based on what you are protecting. Use a tenant to enforce fairness, a route to protect a workload, and a fleet-level limit to protect a shared bottleneck. Charge one token for opening an upload or more tokens for expensive work if you can estimate its cost. Limit upload bytes and outstanding uploads independently, because direct transfer to object storage bypasses the API after the credential is issued. Reserve usable bandwidth for existing uploads before admitting new work. For protection across multiple budgets, define which checks must be atomic or how reservations are reversed when a later check rejects.
| Control | Example | Acts on |
|---|---|---|
| Token bucket | Six-token burst, two tokens per second | New upload reservations |
| Monthly quota | 10 GiB stored per tenant | Total retained bytes or billed usage |
| Concurrency | Four scans active per tenant | Slots held by running jobs |
| Queue-admission bound | Reject optional work when oldest age passes its budget | Unfinished admitted work |
Calculate a token bucket
Let B be the bucket capacity in tokens, r the refill rate in tokens per second, x the stored token balance, Δ t elapsed seconds, and c the cost of this operation in tokens. Refill to x'=min(B,x+rΔ t). If c ≤ x', admit the operation and store x'-c. Otherwise reject it and preserve the refilled balance. The refill, decision, and resulting state should be updated atomically for a shared scope. Keep the timestamp consistent with the updated balance, including when a request is rejected.
Let B=6 and r=2. At time zero the full bucket admits a cost-five upload, leaving one token. At second one it has 1+2=3 tokens. It rejects a cost-four request and stores balance three at that time. At second two it has five tokens, admits cost four, and leaves one. The system can admit an initial burst of six tokens after enough idle time. Under this policy the most it can admit from a full bucket across an interval of t seconds is B+rt tokens. A request whose cost exceeds bucket capacity cannot become eligible by waiting.
For comparison, a fixed-window counter can admit one full window's worth immediately before a boundary and another immediately after. A sliding log keeps exact event history for its window at the cost of more state. A token bucket makes burst allowance explicit without keeping an entry per request. The design and Redis-specific trade-offs are explored further in Designing a Distributed Rate Limiter.
Diagram key and text version
- Entry
- Process
- Outcome
- Upload request → Check budget: identify caller
- Check budget → Reserve upload: within budget
- Check budget → Return 429: rate exceeded
RFC 6585 defines 429 Too Many Requests and permits Retry-After. RFC 9110 defines the form of that header, including whole seconds or an HTTP date. Return a conservative delay when you can calculate one. A caller can still be rejected after the delay if competitors consume the next tokens. Use a different response for a validation error or a global service outage, so callers can tell which changes may help.
Decide what happens when limiter state is unavailable
A local bucket is cheap and continues working when a shared datastore fails, but each instance has its own balance. Three instances each configured for two tokens per second and burst six can admit a combined six tokens per second and burst eighteen. If you need a fleet-wide limit, route decisions to a shared atomic state transition or allocate bounded per-instance or per-region budgets. Allocation can strand capacity while another region rejects requests.
Protect costly new uploads conservatively during a policy-store outage, and preserve previously accepted work. For benign public searches, a bounded local limit or a cheaper degraded response may be appropriate. Record that fallback traffic used a different policy. A suggested fallback is meaningful only if you can state its aggregate ceiling across all instances.
Use discovery and versioned configuration#
Service discovery tells a client which healthy endpoints implement a logical service name. It may use DNS, a registry, or a proxy with a control plane. For example, a Kubernetes Service provides a stable address or discovery mechanism and tracks backends through EndpointSlices. Readiness propagation is asynchronous. A client still needs connection timeouts, refresh rules, and recovery from a stale destination.
Configuration supplies values such as allowed MIME types, upload size, indexing policies, or token rates. Roll them out with a version, validation, and an observed propagation target. Treat sensitive credentials separately from ordinary configuration. In Kubernetes, a mounted ConfigMap can update after propagation, while values consumed as environment variables require a Pod restart to change. Whether a file-based setting takes effect also depends on application reload behavior. Monitor the effective policy version, so an unexplained difference between replicas can be investigated.
A smaller bucket capacity needs an explicit transition. Clamp stored balances to the new cap, or choose a deliberately initialized new version and budget its initial burst. During mixed policy versions, compute the temporary maximum allowed work. A configuration change that silently resets every bucket to full can create a sudden correlated burst.
Diagnose by tracing an item and a request#
| Symptom | Check first | Recovery path |
|---|---|---|
| Upload says complete but deck is missing | Object version, scan status, catalog state, and publication event | Retry verification or reconcile an orphan |
| Published deck fails to appear in search | Revision, consumer lag, rejected events, and refresh | Repair processing or rebuild the projection |
| Revoked deck still appears | Search authorization filters and revision lag | Deny through authority and reconcile removal promptly |
| A single tenant delays scans for others | Reserved bytes, running jobs, and age by tenant | Isolate concurrency and bound admissions |
| 429s jump after deployment | Scope, effective policy version, clock, and bucket state | Restore the intended policy with explicit balance transition |
In an interview, start with quantities and access patterns. Decide which bytes and metadata are authoritative, draw the upload and publication transitions, and explain how the index catches up and rebuilds. Size request, bytes, and scanning capacity separately. Write a clear fairness and failure policy, and name the measurements that distinguish true overload from a stale configuration or an unhealthy route.
Run the Python lab#
Download the lab and run python3 09-object-storage-search-rate-limits.py with Python 3.10 or newer. It operates on local metadata events. It builds posting sets, rejects a delayed event after a versioned delete, and compares token decisions with the worked example. The model is single-process and uses integer seconds and tokens. A distributed limiter needs atomic shared updates or a bounded budget allocation, a trustworthy shared time model, and behavior for state loss.
Try it yourself
Repair a reordered delete
The index receives revision 12 deleting a deck, then revision 11 renaming it. A nightly job rebuilt the index from live documents only and discarded all tombstones. How can the deck reappear, and what should the rebuild retain?
Reveal solution
The delayed revision 11 sees no record of the deleted item's revision. Preserve version floors until the replay and late-delivery horizon has passed, or use a snapshot boundary and replay protocol that prevents old changes from arriving after the rebuild. The authority remains responsible for current access.
Try it yourself
Budget the worst-case burst
Four independent API replicas each have a 15-token bucket refilling at four tokens per second. What immediate burst and long-run refill can the fleet admit? If the product promises a 15-token fleet-wide burst, what must change?
Reveal solution
The fleet can admit 60 tokens immediately and replenish 16 per second. Use an atomic shared budget or split the burst and refill limits into allocations whose sum meets the fleet-wide contract. Check policy during failover and rollout too, when independent replicas or replacement buckets may overlap.
Memory chart#
Object store versioned bytes and integrity checks
Catalog ownership, visibility, and publication
Search analyzed terms → postings → filtered candidates
Recovery snapshot + changes + version-aware apply
Admission identity + rate + burst + quota + concurrency
Operations monitor age, bytes, policy versions, and paid cost
The next module starts with reliable, scalable, and maintainable systems. You will revisit these building blocks through the guarantees and failure domains of the data systems behind them.
References#
- Designing Data-Intensive Applications, first edition, Chapter 3, relates full-text search and fuzzy lookups to query patterns and index structure.
- Amazon S3 data consistency, presigned URLs, and multipart uploads define object-level behavior and capability boundaries.
- Lucene PostingsEnum and Elasticsearch near real-time search describe postings and refresh visibility.
- RFC 2697, A Single Rate Three Color Marker describes capped token refill for network traffic. The API example uses a single bucket with application-defined costs.
- RFC 6585, Additional HTTP Status Codes and RFC 9110, HTTP Semantics specify 429 and Retry-After behavior.
- Kubernetes Services and ConfigMaps illustrate endpoint discovery and configuration propagation.