Building a Local Business Review Service and a Link Shortener
System DesignModel answerLast updated
Design a location-aware business discovery and review platform, then a short-link service, covering data models, search, caching, scaling reads and writes, and operational trade-offs.
You are asked to design two services in one session. Plan on spending roughly two-thirds of your time on the first and one-third on the second.
Part 1: Local business discovery and reviews
Design a platform where people find nearby businesses and read and write reviews.
Cover the following:
- Data model: users, businesses (with coordinates and categories), reviews and ratings, photos, and check-ins. Mention keys and indexes.
- Read scaling: replication, caching, CDN usage, and search indexes.
- Write scaling: sharding, queues and asynchronous pipelines, consistency choices, and how you would run backfills.
- Search: text search and geospatial queries, ranking, and how to keep latency low.
- Cache invalidation and overall performance considerations.
Part 2: Short-link service
Design a service that turns long URLs into short ones and redirects visitors.
Cover the following:
- Key or ID generation and how to handle collisions.
- Storage layout.
- Redirect behavior and CDN usage.
- Rate limiting and abuse control.
- Click analytics.
- Expiry (TTL) and deletion.
- Custom aliases.
- How to scale for heavy read and write traffic.
State your assumptions about scale up front, sketch the architecture, and call out the trade-offs you are making.
Hints
Hint 1
Start with numbers: both systems are heavily read-dominated, so estimate QPS, storage per entity, and the read:write ratio before choosing components. Business metadata is small, reviews are medium, photos are huge.
Hint 2
For nearby search, think in terms of a spatial index (geohash with neighbouring cells, quadtree, S2/H3, or a search engine's geo_point) followed by an exact distance filter. Rank with a smoothed rating rather than a raw average.
Hint 3
Keep the user-facing write path short and synchronous (idempotent insert), then push everything else (aggregates, reindexing, cache invalidation) through a change stream to asynchronous consumers.
Hint 4
For the shortener, compare hashing the URL, random codes, and a counter encoded in base62. Decide how each handles collisions, predictability, and coordination across servers, and make the redirect path cacheable.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
How I would frame it
Both systems are read-heavy, so the shared toolkit is caching, a CDN, replication, and asynchronous pipelines. The hard problems differ: geospatial search and ranking for the review platform, and ID generation plus redirect latency for the shortener.
Part 1: Business discovery and reviews
Requirements and scale
- Functional: search nearby by text, category, rating, price, "open now"; view a business; post reviews and ratings; upload photos; check in.
- Non-functional: search p99 under about 200 ms, high availability, eventual consistency for ratings and search, but read-your-writes for a user's own review.
- Estimates: 50M daily users at 10 searches each is about 500M searches/day, roughly 6K QPS average and 20K at peak. Writes are small: around 200K reviews and 1M photos per day, so reads outnumber writes by 100:1 or more.
- Storage: 10M businesses at 2 KB is about 20 GB; 500M reviews at 1 KB is about 500 GB; 2B photos with variants is on the order of 2 PB. So business metadata fits in memory and a search index, reviews need sharding, and photos go to object storage behind a CDN.
API sketch
GET /search?q&lat&lng&radius&category&open_now&sort&cursorGET /businesses/{id}andGET /businesses/{id}/reviews?cursorPOST /businesses/{id}/reviewswith an idempotency keyPOST /photos/upload-urlreturning a pre-signed URL so clients upload straight to object storage
Use cursor pagination, not offsets, which are slow and unstable on large lists.
Data model
- Users:
user_id, name, unique email, review count. - Businesses:
business_id, name, lat/lng, geohash, address, hours with timezone, price,avg_rating,review_count,rating_sum, status. A join table maps businesses to categories. Indexes ongeohashand(category, geohash). - Reviews: time-ordered
review_id,business_id,user_id, rating 1-5, text, timestamps, status. Shard bybusiness_idbecause the dominant query is "reviews for this business". Index(business_id, created_at DESC)and enforce a unique(business_id, user_id). Keep auser_reviewslookup sharded by user for profile pages. - Photos: metadata only (id, business, user, object key, dimensions, moderation state). Bytes live in object storage.
- Check-ins: append-only and high volume, so a wide-column store partitioned by business and clustered by timestamp fits; keep counters separately.
Stores: a relational DB for users, businesses and reviews; Elasticsearch/OpenSearch as a derived search index; Redis for caches and counters; object storage plus CDN for photos.
Architecture
Clients hit the CDN, then an API gateway (auth, rate limiting), then stateless Search, Business, Review, Media and Check-in services. Writes go to the primary database. Change data capture streams the log into Kafka, and consumers update the search index, recompute rating aggregates, invalidate caches, and feed spam and ranking pipelines. Photos use a pre-signed upload, a storage event, a worker that makes thumbnails and runs moderation, and CDN delivery.
Geospatial search
- Geohash: a precision-6 cell is roughly 1.2 km by 0.6 km. Query the user's cell plus its 8 neighbours to avoid boundary misses, then filter by exact haversine distance.
- Quadtree: adapts to density (small cells in dense cities); 10M points fit in a few GB of memory.
- S2/H3: common in production.
- Practically, use a search engine with a
geo_pointfield and ageo_distancefilter combined with BM25 text matching on name and category.
Ranking blends distance decay, a Bayesian-smoothed rating (C·m + sum) / (C + n) (so one 5-star review does not beat 500 reviews averaging 4.6), popularity, and personalization.
Scaling search: shard the index by region since queries are local, add replicas for throughput, and cache popular (geohash, category, filters) results for 1-5 minutes. Compute "open now" at query time from hours and timezone rather than indexing it.
Scaling reads
- Read replicas for business pages and review lists. For read-your-writes, pin a user to the primary for a few seconds after they post, or merge their pending review client-side.
- Cache-aside in Redis for business objects and the first review page.
- CDN for photos, static assets, and optionally anonymous pages with short TTLs.
- Precompute
avg_ratingandreview_count; never runAVG()on the read path.
Scaling writes
- Shard reviews by
business_id. Hot businesses are a read problem, solved by caching, since write rates per business are low. - The review POST does one idempotent insert and returns. Aggregates, reindexing, notifications and spam scoring run asynchronously.
- Aggregates are updated atomically (
rating_sum += r,count += 1), with edits applied as deltas and deletes as subtractions. A periodic reconciliation job recomputes truth to fix drift. - Check-in counters use Redis
INCR, flushed to the database in batches. - Backfills and reindexing: build a new index from a snapshot, replay the change stream from the snapshot offset, dual-write during transition, verify counts and checksums, flip an alias, and throttle so live traffic is not starved.
Cache invalidation
Update the database, then delete the cache key (delete, not set, to avoid write races). Drive invalidation from the change stream so every writer is covered, including admin tools. Keep a TTL as a safety net, and use versioned keys for CDN content. Protect hot keys against stampedes with request coalescing or a short lock, and add jitter to TTLs.
Part 2: Short-link service
Requirements and estimates
Assume 100M new links per month and a 100:1 read ratio, so about 40 writes/s and 4K redirects/s on average, with much higher peaks. Redirect latency matters most.
ID generation
- Counter encoded in base62: 7 characters give about 3.5 trillion codes. A central counter is a bottleneck, so hand out ID ranges (for example blocks of 10K) to each app server. There are no collisions, but codes are guessable; apply a reversible shuffle if enumeration matters.
- Random codes: generate and insert with a unique constraint, retrying on collision. Simple and unguessable, with rare retries at this keyspace size.
- Hash of the URL: deterministic deduplication, but truncation causes collisions that need a salt-and-retry step. Usually not worth it.
Storage
A key-value store (DynamoDB, Cassandra, or sharded MySQL) keyed by short code, with the long URL, owner, created time, expiry, and flags. Access is almost purely point lookups, so it shards easily by code. A secondary index by owner supports dashboards. Custom aliases go into the same keyspace with a conditional insert, so a taken alias is rejected atomically; reserve blocklisted and system words.
Redirects and CDN
Look up in Redis first, then the database. Return 301 for permanent links (cacheable, fewer hits) or 302 when you need every click counted or links can change. Popular codes can be cached at the CDN edge with a short TTL, trading a little analytics precision for latency.
Rate limiting and abuse
Token bucket per API key and per IP at the gateway, backed by Redis. Scan submitted URLs against malware and phishing lists, and cap link creation for anonymous users.
Analytics
Do not write counts on the redirect path. Emit a click event (code, timestamp, coarse geo, user agent, referrer) to a queue and aggregate in a stream processor into a columnar or time-series store. Counts are eventually consistent.
TTL and deletion
Store an expiry timestamp and check it on read, so expired links stop working immediately. Reclaim space lazily with a background sweeper or the store's native TTL. Avoid reusing expired codes for a cooling-off period so old links do not point to unrelated content.
Scaling
Stateless redirect servers behind a load balancer, a large Redis cache (the hot set is small and follows a power law), database sharding by code, and multi-region replication for latency and availability. Writes are low volume, so the primary concern is read latency and cache hit rate.
Common mistakes
- Computing average ratings at read time.
- Using offset pagination on huge lists.
- Doing indexing, aggregation and notifications inside the user-facing write request.
- Forgetting neighbouring cells in geohash queries.
- Choosing a single global counter for ID generation without range allocation.
- Writing analytics synchronously on the redirect path.
- Ignoring cache stampedes and hot keys.