Multi-Tenant Labeling Service: API Contract and Storage Design
System DesignModel answerLast updated
Design a workspace-scoped labeling service with REST endpoints, a schema, a search strategy for AND/OR filtering, and handling of concurrency, idempotency and pagination.
You are building a labeling service for a multi-tenant collaboration product. Users create labels (tags) in a workspace and apply them to items such as pages or issues. Those items are owned by other services, so your service only stores references to them.
Operations to support
- Create a label.
- Rename a label.
- Delete a label.
- Apply or remove one or more labels on an item.
- List the labels on a given item.
- Find items by one or more labels, with both "has all of these" (AND) and "has any of these" (OR) semantics.
Rules and quality requirements
- Label names are unique within a workspace.
- Applying and removing labels must behave sensibly under concurrent requests and client retries (idempotency).
- Every list and search endpoint must be paginated.
What to deliver
- A set of REST endpoints with example requests and responses.
- A data model or database schema.
- An indexing and query strategy for label-based search.
- How you handle edge cases, at minimum: deleting a label that is still applied to items, renaming a label to a name that already exists, and bulk operations.
State your scale and consistency assumptions explicitly, and explain the trade-offs behind your choices.
Hints
Hint 1
Give labels a stable surrogate ID and use that ID in attachment URLs, so renames never touch the attachment data. Decide how to normalize names (case, whitespace, Unicode) for the uniqueness check.
Hint 2
Model applying a label as a sub-resource of the item and use PUT/DELETE so they are naturally idempotent. Reserve idempotency keys for POST-style calls such as batch changes. Use a version or ETag for concurrent renames.
Hint 3
A composite primary key on (workspace, item type, item id, label id) answers 'labels of an item'. A second index led by (workspace, label id) answers 'items with a label'. AND search is a count-and-compare over the requested labels, with keyset pagination.
Hint 4
Think about when relational queries stop being enough (huge labels, combined text or status filters) and what a search index plus change-data-capture would cost in staleness and permissions.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
This is primarily an API-contract question, with storage second. I would spend the first few minutes on assumptions, then the bulk of the time on the API.
Assumptions
- Multi-tenant: labels belong to a workspace and can be applied to any item type. Items live in other services, so we store only
(type, id)references. - Name uniqueness is case-insensitive per workspace ("Backend" equals "backend"). Names are normalized with trim, Unicode normalization and lowercasing.
- Labels have a stable ID, so rename is a single-row update.
- Scale: the largest workspace has about 10M items, 50k labels and about 5 labels per item (roughly 50M attachment rows). Reads outnumber writes about 100:1. Targets: list-labels-on-item under 50 ms p99, search under 200 ms p99.
- Search results must respect the caller's permissions.
REST API
Base path /v1/workspaces/{ws}; the tenant is always in the path.
Labels
POST /tags Idempotency-Key: <uuid>
{ "name": "Backend", "color": "#0052CC" }
-> 201 Created, Location: /tags/tag_123, ETag: "1"
-> 409 { "error": "TAG_NAME_CONFLICT", "existingTagId": "tag_088" }
GET /tags?prefix=back&limit=50&cursor=... -> { items, nextCursor }
GET /tags/{tagId} -> 200 | 404
PATCH /tags/{tagId} If-Match: "1"
{ "name": "backend-services" }
-> 200 + new ETag | 409 (name taken) | 412 (stale version)
DELETE /tags/{tagId} -> 204 (repeat calls also 204)
POST /tags/{tagId}:merge { "intoTagId": "tag_088" } -> 202 { jobId }
Applying labels (sub-resource of the item)
PUT /entities/{type}/{id}/tags/{tagId} -> 204 (already applied: still 204)
DELETE /entities/{type}/{id}/tags/{tagId} -> 204 (not applied: still 204)
PUT and DELETE are idempotent by definition, so retries are safe without keys.
Batch on one item (atomic)
POST /entities/page/p42/tags:batch Idempotency-Key: <uuid>
{ "add": ["tag_123","tag_200"], "remove": ["tag_007"] }
-> 200 { "tags": [...] }
Batch across many items (non-atomic, per-item results)
POST /tag-operations
{ "op":"attach", "tagIds":["tag_123"], "entities":[{...},{...}] }
-> 200 { "results":[{"entity":"A","status":"ok"},{"entity":"B","status":"error","code":"ENTITY_NOT_FOUND"}] }
Above a threshold (say 1,000 items), return 202 and a job resource to poll.
Read and search
GET /entities/{type}/{id}/tags?limit=100&cursor=...
GET /entities?tagIds=t1,t2&match=all|any&type=issue&limit=50&cursor=...
Design points:
- IDs in paths, not names, since names change and need URL encoding.
- Opaque keyset cursors, not offsets: offsets get slow on deep pages and skip or duplicate rows under concurrent writes.
- Cap
limit(for example 100) and the number of labels per search (for example 10). - A single consistent error envelope.
Data Model (Postgres, sharded by workspace_id)
CREATE TABLE tags (
workspace_id BIGINT NOT NULL,
tag_id BIGINT NOT NULL,
name TEXT NOT NULL, -- display form
name_norm TEXT NOT NULL, -- normalized for uniqueness
color TEXT,
version INT NOT NULL DEFAULT 1,
usage_count BIGINT NOT NULL DEFAULT 0, -- approximate, async
deleted_at TIMESTAMPTZ,
PRIMARY KEY (workspace_id, tag_id)
);
CREATE UNIQUE INDEX uq_tag_name ON tags (workspace_id, name_norm)
WHERE deleted_at IS NULL;
CREATE TABLE entity_tags (
workspace_id BIGINT, entity_type SMALLINT, entity_id TEXT, tag_id BIGINT,
created_at TIMESTAMPTZ,
PRIMARY KEY (workspace_id, entity_type, entity_id, tag_id)
);
CREATE INDEX ix_tag_entities
ON entity_tags (workspace_id, tag_id, entity_type, entity_id);
CREATE TABLE idempotency_keys (
workspace_id BIGINT, key TEXT, request_hash TEXT,
response JSONB, expires_at TIMESTAMPTZ,
PRIMARY KEY (workspace_id, key)
);
Each index on entity_tags serves one access pattern: labels of an item (primary key) and items with a label (secondary index). Both are single range scans. The partial unique index enforces name uniqueness at the database level, which is the only race-free way to do it.
Search
OR:
SELECT DISTINCT entity_id FROM entity_tags
WHERE workspace_id=$1 AND entity_type=$2 AND tag_id = ANY($3)
AND entity_id > $cursor
ORDER BY entity_id LIMIT $limit;
AND:
SELECT entity_id FROM entity_tags
WHERE workspace_id=$1 AND entity_type=$2 AND tag_id = ANY($3)
AND entity_id > $cursor
GROUP BY entity_id HAVING COUNT(*) = cardinality($3)
ORDER BY entity_id LIMIT $limit;
The composite primary key prevents duplicate pairs, so COUNT(*) equals the number of distinct matching labels. Posting lists in ix_tag_entities are already ordered by entity_id, so the planner can merge them and stop early at the limit. Start from the rarest label using usage_count.
When this is not enough: labels with millions of items, searches that mix labels with text, status or date filters, or relevance sorting. Then add OpenSearch/Elasticsearch with one document per item holding tagIds, type, updatedAt and ACL fields. AND maps to multiple term filters (or terms_set), OR to one terms filter, and pagination to search_after. Feed it from the database via a transactional outbox and CDC, and state the roughly one-second staleness openly. Index label IDs rather than names, so a rename needs no reindex.
Permissions: apply ACL filters inside the query or index, never after pagination, or pages will be short and may leak existence.
Concurrency and Idempotency
- Rename: optimistic concurrency with
versionandIf-Match; return 412 on mismatch. The unique index decides name collisions and returns 409. - Attach:
INSERT ... ON CONFLICT DO NOTHING. Detach: a plainDELETE. Both are safe to retry. - Batch and create POSTs:
Idempotency-Keystored with a request hash. The same key with the same body replays the stored response; the same key with a different body returns 422. - usage_count: update asynchronously, because a synchronous counter becomes a hot row on popular labels. Treat it as approximate.
Edge Cases
- Delete a label that is in use: soft-delete the label (
deleted_at) so the name is freed and reads hide it immediately. Remove attachment rows in a background job in chunks. Alternatively return 409 unless?force=true. Prefer soft delete plus async cleanup so the delete call stays fast. - Rename collision: return 409 with the existing label's ID, and offer
:mergeas the resolution path. Case-only renames of the same label must succeed (compare against other rows, not itself). - Bulk operations: atomic for a single item, per-item results for cross-item operations, a hard size cap, and async jobs beyond it. Deduplicate IDs in the request. Reject unknown label IDs up front.
- Attaching a deleted label: return 404 or 409.
- Orphaned items: if an item is deleted in the owning service, consume its delete event and remove its rows.
Common Mistakes
- Using names as identifiers in URLs or attachment rows, which makes renames expensive.
- Checking uniqueness in application code instead of with a unique index.
- Offset pagination on search.
- Making attach a non-idempotent POST.
- Filtering permissions after pagination.
- Ignoring hot labels and synchronous counters.