Thread-Safe Sharded Like Counter With Periodic Batch Flush

Last updated: November 29, 2026

Quick Overview

Implement an in-process like counter for a video service: many request threads call like(video_id) concurrently, and a background flusher periodically drains the accumulated counts to the database. No like may be lost or double counted, and request threads should rarely block each other.

TikTok
Software Engineering Fundamentals
Software Engineer
TikTok
November 29, 2026
Software Engineer
Onsite
Software Engineering Fundamentals
Medium

0

0

0 solved


Implement an in-process like counter for a video service: many request threads call like(video_id) concurrently, and a background flusher periodically drains the accumulated counts to the database. No like may be lost or double counted, and request threads should rarely block each other.

A viral TikTok video can receive tens of thousands of likes per second, so services buffer increments in memory and write in batches. This onsite fundamentals question checks race conditions, lock granularity, and the atomic swap pattern for flushing.

What the Interviewer Expects
  • Identifies the read-modify-write race on a shared dict
  • Uses lock striping (several shards with their own locks) to reduce contention
  • Flushes by swapping each shard's dict under its lock, then writing outside the lock
  • Explains what happens to counts if the process crashes between flushes
  • Writes a concurrent test that proves no increments are lost
Key Topics to Cover
concurrency
lock striping
race conditions
batching
atomic swap
How to Approach This
  1. Apply SOLID principles. Single Responsibility makes code testable, Open/Closed makes it extensible.
  2. Choose data structures based on access patterns, not familiarity.
  3. Prefer immutable data and message passing over shared mutable state for concurrency.
  4. Design APIs with RESTful conventions, versioning, meaningful errors, and pagination from day one.
Possible Follow-up Questions
  • How would you make the counter durable across process crashes?
  • Why might a lock-free approach not actually be faster in CPython?
  • How would you handle a database write failure during flush without losing or double counting?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice System Design Problems
Sample Answer
Requirements
  • like(video_id) is called from many threads.
  • drain() returns all counts accumulated since the last drain and resets them, without blocking like for long.
  • No lost updates and no double count...
High-Level Design

counts[v] += 1 is a read, add and write; two threads can interleave and lose an increment, so access must be synchronized. A single global lock works but serializes all requests. Lock striping: N sh...


Submit Your Answer
Markdown supported