Abstractions in system design
easy 22 minAn abstraction hides how something works behind a small, stable interface, so callers only need to know what it does.
See it run
One request walks through the layers, the storage is swapped underneath, and the leak shows itself.
Operations
First read
Client code asks for user 123. Each layer asks the one below and knows nothing more.
Step 1 of 7
The client calls the service
get_user("123"). The client knows one method and nothing about storage.
Step 1: The client calls the service
def get_user(self, user_id): # service return self.users.find_by_id(user_id)def find_by_id(self, user_id): # cached repository hit = self.cache.get(f"user:{user_id}") if hit is not None: return User(**json.loads(hit)) user = self.inner.find_by_id(user_id) # database if user: self.cache.set(f"user:{user_id}", to_json(user), ttl=300) return user- Reads the database
- Once
- Callers change
- None
Say what each layer knows and what it does not know. That is the whole point of layers.
In the real world
The same abstractions in system design doing real jobs. Pick one and step through it.
Encapsulation between services: who may touch the balance?
Step 1 of 2
Open
Invalid state
The shop writes to the account database directly and sets a balance of minus 1,000. Nothing stops it.
Step 1: Open
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Storage details in the interface
majorCallers start to depend on SQL or cursors, so the storage can no longer change.
Wrongdef find(self, sql, cursor): ...Rightdef find_by_id(self, user_id): ...Treating a remote call as local
criticalA networked implementation can be slow or unreachable. Without a timeout the caller waits.
Wronghit = redis.get(key)Righttry: hit = redis.get(key) # client built with a timeoutexcept CacheError: hit = None # a missBuilding dependencies inside
majorThe class cannot be tested or rewired without editing it.
Wrongclass UserService: def __init__(self): self.users = PostgresRepository("db:5432")Rightclass UserService: def __init__(self, users): self.users = usersForgetting to drop the cached copy
majorThe wrapper promises to behave like the repository. Returning an old user right after a save breaks that promise.
Wrongdef save(self, user): self.inner.save(user)Rightdef save(self, user): self.inner.save(user) self.cache.delete(f"user:{user.id}")
Interview tips
How to explain it
- Interface: what. Implementation: how.
- Layers: presentation, service, repository, infrastructure.
- Each layer asks the one below.
Memory trick: HIDE
- Hide complexity.
- Interface defines the contract.
- Decouple concerns, encapsulate state.
Reach for it when
- A decision is likely to change.
- Many callers repeat the same details.
- Tests need a fake.
Admit the leaks
- Time: is it local or remote?
- Failure: can it be down?
- Limits and stale data.