Build a Multi-Tenant Tag Index That Scales to Billions
System DesignModel answerLast updated
Design a tagging system supporting tag lifecycle, boolean item queries, autocomplete, and high read/write throughput across thousands of tenants.
Scenario
Your company offers a SaaS platform where each tenant's workspace contains millions of resources — documents, tasks, tickets, or similar entities. Product wants to ship a tagging feature: any resource can carry multiple tags, users can search by tag, and the feature must hold up at scale.
You are asked to design this system from scratch. Walk through your reasoning at each step.
What the system must do
-
Tag lifecycle — Create a new tag or return an existing one by name. Attach one or more tags to a resource, remove them, and make sure the same tag cannot be attached to the same resource twice.
-
Single-tag lookup — Given a tag, return all resources that carry it. Support pagination and ordering (for example, most recently tagged first).
-
Boolean tag queries — Return resources matching a set of tags combined with AND (intersection) or OR (union), or a mix of both.
-
Top-N retrieval — Efficiently surface the top N resources for a tag, ranked by recency or a relevance score.
-
Tag counts — Return how many resources carry each tag, cheaply and at high request rates.
-
Autocomplete and suggestions — Offer prefix-based tag name completion as the user types. Optionally surface tags that frequently appear alongside a queried tag.
-
Data model and storage — Define the schema and choose the right storage technology for tags, resources, and the assignments that link them.
-
Indexing — Describe your forward index (resource → tags), inverted index (tag → resources), and how you handle very large or heavily skewed posting lists.
-
Caching — What you cache, how you expire or invalidate it, and how you handle hot keys.
-
Sharding and multi-tenancy — How you partition data across nodes, isolate tenants, and protect against hot-tag hotspots.
-
Consistency — Choose and justify a consistency model. Explain how you support read-your-writes after a tag is attached.
-
Tag de-duplication, rename, and merge — What happens when the same concept exists under two tag names, when a tag is renamed, and when two tags are merged into one.
-
Access control — How tenant data is isolated and how per-resource ACL filtering fits into query results.
-
Pagination — Design a stable, scalable pagination strategy that holds up under concurrent writes.
-
Backfill and cleanup — How you reindex existing data, and how you clean up orphan tags and counters that have drifted.
-
Capacity, observability, and SLOs — Rough order-of-magnitude sizing, the metrics you would instrument, and the latency and availability targets you would propose.
What is expected
This is an open-ended design question. A strong answer reasons about trade-offs rather than listing technologies. Cover scale assumptions upfront, justify your storage and indexing choices, and explain where you accept eventual consistency and why. Concrete numbers and back-of-envelope math are expected. Mention failure modes and how you mitigate them.
Hints
Hint 1
Start with scale: estimate the number of tenants, resources, tags, and assignments before picking any technology. The resulting data volume will drive every storage and sharding decision that follows.
Hint 2
Separate your source of truth (the OLTP store that enforces uniqueness and handles writes) from your derived read views (inverted index, search cluster, counters). Use a CDC pipeline to propagate changes rather than dual-writing from the application layer.
Hint 3
Think about skew early. A tag used on 50 million resources needs a different read path than one used on 50. Consider bucket-partitioning the inverted index for oversized posting lists and keeping a capped in-memory sorted set for the top-N hot-tag case.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Size the Problem First
State your assumptions before drawing any boxes. The numbers shape every decision.
- Tenants: ~100K workspaces; ~10B taggable resources total; ~5 tags per resource → ~50B tag assignments, ~100M distinct tag names.
- Traffic: ~20K tag writes/s at peak, ~200K reads/s (roughly 10:1 read-heavy).
- Skew: a single popular tag like
bugin a large tenant can hold 50M resources; most tags hold fewer than 100. - Latency targets: single-tag reads p99 < 100 ms, boolean queries p99 < 300 ms, index propagation lag < 2 s.
Storage math: one assignment row ≈ 100 B → 50B × 100 B = 5 TB raw, doubled for forward + inverted indexes = ~10 TB, ~30 TB with 3× replication. Too large for a single node; sharding is mandatory.
2. API Surface
POST /tags {name} → get-or-create, returns tag_id
POST /resources/{id}/tags {tag_ids[]} → idempotent attach
DELETE /resources/{id}/tags/{tag_id}
GET /tags/{id}/resources?sort=recent&limit=50&cursor=…
GET /resources?all=a,b&any=c,d&sort=recent&cursor=…
GET /tags/{id}/count
GET /tags/suggest?prefix=bac&limit=10
GET /tags/{id}/related
POST /tags/{a}/merge {into: b}
PATCH /tags/{id} {name}
Every call is implicitly scoped to tenant_id extracted from the auth token — never from client input.
3. Data Model and Storage
The source of truth is a sharded relational store (Postgres via Vitess, or similar), sharded by tenant_id so a tenant's data is co-located and transactions stay local.
-- Tags
tags(tenant_id, tag_id, name, normalized_name,
status {active|merged|deleted}, merged_into,
usage_count, created_at)
UNIQUE (tenant_id, normalized_name)
-- Forward index: resource → tags (prevents duplicates via PK)
resource_tags(tenant_id, resource_id, tag_id, created_at, created_by)
PRIMARY KEY (tenant_id, resource_id, tag_id)
-- Inverted index: tag → resources (lives in Cassandra / DynamoDB)
tag_resources(tenant_id, tag_id, bucket, sort_ts DESC, resource_id)
PARTITION KEY: (tenant_id, tag_id, bucket)
CLUSTERING: (sort_ts DESC, resource_id)
- Duplicate prevention: the composite primary key on
resource_tagsmakes attach idempotent viaINSERT … ON CONFLICT DO NOTHING. - Get-or-create:
INSERT … ON CONFLICT (tenant_id, normalized_name) DO NOTHING RETURNING tag_id, fall back to a SELECT on conflict. - Search cluster (OpenSearch): stores resource documents with
tags[], ACL fields, and sort fields. Serves complex boolean queries and autocomplete; not the source of truth. - Change propagation: CDC via Debezium → Kafka fans out to the inverted index writer, search indexer, counter aggregator, and cache invalidation. No dual-writes from the app.
4. High-Level Architecture
Client → API Gateway (auth, tenant) → Tag Service ──► OLTP (sharded by tenant_id)
│ │ CDC
▼ ▼
Redis cache ◄──── Kafka ─► Indexer ──► Inverted index (Cassandra)
├──────────► Search (OpenSearch)
├──────────► Counter service
└──────────► Offline jobs (co-occurrence, reconciliation)
5. Key Design Decisions
Queries
Single-tag and top-N. The Cassandra partition is clustered by sort_ts DESC, so "latest N items" is one range scan. For hot tags, maintain a capped Redis sorted set (top ~1,000 items by score) that the indexer updates on every write. Pages beyond the cache depth fall through to the store.
Boolean queries.
- AND: check tag cardinalities first, then probe the smallest posting list and verify membership in the forward index for each candidate. For large intersections, delegate to OpenSearch where bitset intersection across inverted posting lists is efficient.
- OR: k-way merge of per-tag sorted streams, deduplicating by
(sort_ts, resource_id). - Rule: small, simple queries hit the KV store; large or structurally complex ones route to search.
Counts. Never run COUNT(*) on the request path. The CDC consumer applies +1/−1 deltas to sharded counters (N sub-rows per popular tag, summed on read) and caches the aggregate with a short TTL. Counts are labeled approximate for very large tags.
Autocomplete. Edge-n-gram field on normalized_name in a per-tenant tag index in OpenSearch, ranked by usage_count. For smaller tenants, a Redis ZRANGEBYLEX structure also works. Target p99 < 50 ms; debounce on the client.
Related tags. An offline Spark job computes co-occurrence per tenant, ranks pairs by PMI, and stores the top 20 per tag.
Hot and High-Cardinality Tags
When a tag's posting list exceeds a threshold (e.g., 1M resources), split its Cassandra partition across bucket = hash(resource_id) % B. Writes spread across buckets; reads scatter-gather, take the top-k from each bucket, and merge. The value of B is stored in tag metadata so both readers and writers agree.
Caching Strategy
- Tag metadata (name → id, id → tag object): aggressive caching with long TTL; invalidate via CDC on rename or merge.
- First result page and count per tag: short TTL (~30 s) plus event-driven invalidation from the indexer.
- Hot keys: in-process L1 cache (1–5 s TTL) + request coalescing (single-flight) on cache misses + key replication across Redis nodes (e.g.,
key#0…key#9). - Never cache ACL-filtered results across users. Cache the unfiltered candidate list and filter per-request based on the caller's permissions.
Sharding and Isolation
- OLTP shards by
tenant_id. Large tenants get dedicated shards or are sub-sharded byhash(resource_id). - Inverted index partitioned by
(tenant_id, tag_id, bucket). - OpenSearch uses per-tenant routing keys; enterprise tenants get dedicated indices.
- Per-tenant rate limits and write quotas prevent noisy-neighbor issues.
Consistency Model
The OLTP layer is strongly consistent — a single-shard transaction enforces uniqueness and idempotency. Derived views (inverted index, search, counts, caches) are eventually consistent with a p99 propagation lag target under 2 s. Strong consistency across all derived stores would require synchronous cross-system writes, hurting latency and availability with little user-visible benefit.
Read-your-writes: the write response includes a commit version token. The client echoes it on subsequent reads. If the indexer's watermark is behind the token, the service either reads from the OLTP primary directly or merges the caller's recent writes from a short-lived session store into the result set. Most frontends also apply optimistic local updates.
Tag De-duplication, Rename, and Merge
- Normalization: strip whitespace, lowercase, and optionally apply Unicode NFKC before storing
normalized_name. The unique constraint prevents duplicates at creation time. - Rename: update
tags.nameand the search index. If the new normalized name collides with an existing tag, the operation is rejected or forced through a merge. - Merge tag A into B: mark A as
mergedwithmerged_into = B. A background job re-points allresource_tagsrows from A to B in batches, re-indexes affected resources in search, and reconciles counts. During the job, reads on A redirect to B.
Pagination
Use keyset (cursor) pagination over (sort_ts DESC, resource_id). The cursor encodes the last-seen values and is opaque to the client. This avoids OFFSET scans, remains stable under concurrent writes, and works across the distributed inverted index. The tradeoff: you cannot jump to an arbitrary page, but that is rarely needed at this scale.
Backfill and Cleanup
- Reindex: a Kafka-based bulk job replays the forward index in batches, writing to the inverted store and search. Idempotent writes and a per-job watermark make it safe to replay.
- Orphan tags: a nightly job identifies tags with
usage_count = 0for more than N days and marks them inactive. - Counter drift: a weekly reconciliation job recomputes exact counts from the forward index and applies corrections.
Capacity and Observability
Key SLOs: single-tag read p99 < 100 ms, boolean query p99 < 300 ms, attach p99 < 50 ms, index lag p99 < 2 s, 99.9% availability per tenant.
Metrics to instrument: write/read latency by percentile, Kafka consumer lag per topic-partition, cache hit rate, hot-tag count, index lag distribution, error rate by API endpoint, and counter drift magnitude from reconciliation runs.
Common mistakes to avoid: dual-writing to multiple stores from the application (use CDC instead), running count queries on the read path, caching ACL-filtered result sets, using OFFSET pagination on large tables, and treating all tags as uniform (skew is the most common source of production incidents in systems like this).