AlgoViz

Abstractions in system design

easy 22 min

An abstraction hides how something works behind a small, stable interface, so callers only need to know what it does.

Video lesson · Chapter 1 of 6

One call crosses a boundary

0:00 / 3:57

Abstraction in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

An abstraction is a simplified view of something complicated. It tells you what you can ask for and what you will get, and it leaves out how the work is done. A file is an abstraction over blocks on a disk. An API endpoint is an abstraction over the code and data behind it.

The visible part is called the interface. The hidden part is called the implementation. When the interface stays the same, the implementation can be fixed, sped up or replaced while callers carry on as before.

Why it exists

Nobody can hold a whole large system in their head. Abstractions cut it into parts that can be understood, built, tested and changed one at a time.

They also decide what a change costs. If forty places talk to the database directly, changing the database means changing forty places. If they all go through one interface, it means changing one. That is why drawing boundaries is a large part of designing systems.

A short history

  1. 1968

    Edsger Dijkstra's THE operating system is built as a stack of layers, each using only the ones below it.

  2. 1972

    David Parnas describes information hiding: split a program so that each module hides one design decision that is likely to change.

  3. 1974

    Barbara Liskov and Stephen Zilles propose abstract data types: a type known by its operations, not by how it is stored.

  4. 1984

    ISO publishes the OSI model, which describes network communication as seven layers.

  5. 2002

    Joel Spolsky writes the Law of Leaky Abstractions: all non-trivial abstractions, to some degree, are leaky.

Words to know

Interface
The operations callers may use, with their promises. Also called a contract.
Implementation
The code and machines that keep those promises.
Layer
A set of parts with one job that offers services to the layer above.
Encapsulation
Keeping data together with the operations that protect it, and blocking direct access.
Leaky abstraction
One whose hidden details still reach the caller, for example as slowness or odd errors.
Dependency injection
Handing a part the things it needs, instead of letting it create them.
Repository
An interface for loading and saving business objects that hides the storage.

How it works

Step through the idea, or press Play.

Step 1 of 3

Say what is needed. Write the few operations callers really use, in their words

Understand it

Start here

The light switch story

Think of a light switch. You press it and the lamp lights up. You do not know where the electricity comes from, and most days you do not need to.

One switch, and what hides behind the wall
Lamp on

The switch is the interface. The wires, the pole, the panel and the battery are the implementation.

The idea

What you gain

Five benefits

  • Less complexity

    You can use a part without reading its code.

  • Easier maintenance

    A fix stays inside one part.

  • Modularity

    Teams and services can work on separate parts.

  • Reuse

    Many callers share one implementation.

  • Freedom to change

    Replace the inside while the outside stays the same.

You already use these

AbstractionWhat you seeWhat it hides
CarPedalsEngine control
Cash machineButtonsBanking systems
APIEndpointsServer logic and data
File systemPathsDisk blocks and caches
SQLTables and queriesIndexes, join order, pages

Layers

Abstraction layers

Systems are built in layers. Each one hides complexity from the layer above it.

One request through the layers

Users send GET /users/123 to one app machine. Inside it the API endpoint calls the UserService, which calls the cached repository. The repository checks Redis first and asks PostgreSQL only on a miss.
Three layers run inside one program. The cache and the database are the infrastructure below them.

Who does what

LayerJobExample
PresentationUI, controllers, API endpointsRead the request, return JSON
ServiceBusiness logic, workflows, use casesCheck the email, create the user
RepositoryData access abstractionfind_by_id, save
InfrastructureDatabase, cache, message queues, external servicesPostgreSQL, Redis

Each layer should

  • Ask only the layer below, through its interface
  • Hide its implementation
  • Expose a clean interface
  • Handle its own concerns

Each layer should not

  • Know about the layers above
  • Skip layers without a stated reason
  • Leak implementation details
  • Have circular dependencies

A read on a cache miss

The caller and the service never learn that there was a cache.

Interfaces

Interfaces and APIs

An interface is a contract. It specifies what operations exist without dictating how they are implemented. One contract can have many implementations.

TypeScript
interface StorageInterface {  get(key: string): Promise<string | null>;  set(key: string, value: string, ttlSeconds?: number): Promise<void>;  delete(key: string): Promise<boolean>;}// Several implementations, one interfaceclass InMemoryStorage implements StorageInterface { /* ... */ }class RedisStorage implements StorageInterface { /* ... */ }class S3Storage implements StorageInterface { /* ... */ }
S3 can fit this interface, but it has no per-key expiry in seconds. That gap is a leak you must decide about.

Good interface

  • Small and focused
  • Stable over time
  • Free of implementation words
  • Documented, including errors and limits

Bad interface

  • Too large: a god interface
  • Leaks the implementation
  • Changes often
  • Hard to implement

Why one interface saves work

direct: c×mthrough an interface: c+m4×3=12;→;4+3=7\text{direct: } c \times m \qquad \text{through an interface: } c + m \qquad 4 \times 3 = 12 ;\to; 4 + 3 = 7
With cc callers and mm implementations, direct links multiply. Through one interface they add up.

Protect the inside

Encapsulation

Encapsulation bundles data with the operations that work on it and restricts direct access. It is what makes hiding real: clients do not need to know the inside, and they cannot come to rely on it.

The same account, open and closed

Without encapsulationWith encapsulation
user.balance = -1000 sets an invalid valueuser.withdraw(100) checks the balance first
user._cache.clear() breaks hidden stateuser.clear_cache() is a safe operation
In a distributed system the same rule says: only one service writes to its own database.

Composition

Add a cache without touching anyone

CachedUserRepository has the same interface as the repository it wraps. It adds caching on reads and deletes the cached copy on writes. This is composition over inheritance, and it is called the decorator pattern.

Read path inside the wrapper

Caching patterns and their traps are covered in caching.

What the hidden cache does to average read time

T=h tc+(1−h)(tc+td)0.9×1+0.1×(1+10)=2.0 msT = h\,t_c + (1-h)(t_c + t_d) \qquad 0.9 \times 1 + 0.1 \times (1 + 10) = 2.0 \text{ ms}
Assumed: 90% hit rate hh, 1 ms cache, 10 ms database. The interface is the same, the average is five times better, and a miss is slightly worse than before.

Wiring

Dependency injection

Who decides which implementation is used? One place at start-up, often called the composition root. Every other part receives what it needs.

Same interface, two worlds

In tests, the UserService and InMemoryStorage run on one developer's machine in the same process. In production, the UserService on an app machine uses RedisStorage on a separate cache machine over the network. Both use get, set and delete.
One setting changes which storage is built. The service and the repository do not change. The behaviour under failure does.

Choosing at start-up

Honesty

Leaky abstractions

It is tempting to say that swapping in-memory storage for Redis is a change of one line. The wiring changes by one line. The behaviour changes more, and good designers say so.

What leaks when memory becomes Redis

PropertyIn memoryRedisPut in the contract
SpeedWell under a microsecondAbout a network round tripCalls may take milliseconds
FailureCannot be unreachableCan time outCalls may fail: treat as a miss
SharingOne copy per processShared by all processesValues may be changed by others
TypesAny objectBytesValues must be serialised
LifetimeGone on restartSurvives an app restartMay vanish at any time

What to do with a leak

Adding a battery is fixing it underneath. A timeout parameter is making it part of the contract.

Rules

Five best practices

  1. 1

    Program to interfaces

    Depend on abstractions, not on concrete implementations.

  2. 2

    Keep interfaces small

    Interface segregation: several small interfaces beat one large one.

  3. 3

    Avoid leaky abstractions

    Do not expose implementation details such as SQL strings or cursor objects.

  4. 4

    Use dependency injection

    Pass dependencies in rather than creating them inside.

  5. 5

    Design for change

    Find the decisions likely to change and put boundaries there. Do not wrap everything.

Cost

When an abstraction is too much

Every layer adds names to learn and another place to look while debugging. A layer that only forwards calls, or an interface that will never have a second implementation and is never replaced in tests, may not earn its place.

Add one when

  • The decision behind it is likely to change
  • Several callers repeat the same details
  • Tests need a fake
  • Two teams need a fixed contract

Wait when

  • You have seen only one use and are guessing the second
  • The layer would only forward calls
  • Callers need the special feature you would hide
  • The team cannot say what it hides

In system design

Boxes on the whiteboard are abstractions

When you draw a box called "queue" you promise what it does. The interviewer may open any box, so know one level below each: what it promises, what it hides and what leaks. Network calls behind boxes are the subject of RPC, and their public shape is the subject of API design.

Summary

The whole topic in one minute.

An abstraction shows what a part does and hides how. Systems are stacks of them: presentation, service, repository, infrastructure. Each layer asks the one below through an interface, so each can change alone.

Keep interfaces small, stable and free of storage words, inject the implementation, and check that every implementation behaves the same way. Then say honestly what leaks: latency, failure, limits and consistency do not disappear because they are hidden.

  • Show what, hide how, and keep the interface stable.
  • Presentation, service, repository, infrastructure: each layer asks the one below.
  • A repository separates business logic from data access.
  • Wrap to add behaviour, inject to choose the implementation.
  • All useful abstractions leak: put time, failure, limits and consistency in the contract.

Sources