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.
Service, repository, cache and storage
Read it, run it, change a line and run it again.
Loading editor…
Runs as it is. The database repository keeps rows in a dict so you can see the layers without a server. No part above the wiring knows which storage is used.
The same in TypeScript
interface Storage { get(key: string): Promise<string | null>; set(key: string, value: string, ttlSeconds?: number): Promise<void>; delete(key: string): Promise<boolean>;}class InMemoryStorage implements Storage { private data = new Map<string, { value: string; expiresAt?: number }>(); async get(key: string) { const e = this.data.get(key); if (!e) return null; if (e.expiresAt !== undefined && Date.now() >= e.expiresAt) { this.data.delete(key); return null; } return e.value; } async set(key: string, value: string, ttlSeconds?: number) { this.data.set(key, { value, expiresAt: ttlSeconds === undefined ? undefined : Date.now() + ttlSeconds * 1000 }); } async delete(key: string) { return this.data.delete(key); }}// class RedisStorage implements Storage { ... } same three methods, over the networkinterface User { id: string; name: string; email: string }interface UserRepository { findById(id: string): Promise<User | null>; save(user: User): Promise<void>; findAll(): Promise<User[]>; delete(id: string): Promise<boolean>;}class DatabaseUserRepository implements UserRepository { private rows = new Map<string, User>(); // a real one runs SQL async findById(id: string) { return this.rows.get(id) ?? null; } async save(user: User) { this.rows.set(user.id, { ...user }); } async findAll() { return [...this.rows.values()]; } async delete(id: string) { return this.rows.delete(id); }}class CachedUserRepository implements UserRepository { constructor(private inner: UserRepository, private cache: Storage, private ttl = 300) {} async findById(id: string) { const hit = await this.cache.get("user:" + id); if (hit !== null) return JSON.parse(hit) as User; const user = await this.inner.findById(id); if (user) await this.cache.set("user:" + id, JSON.stringify(user), this.ttl); return user; } async save(user: User) { await this.inner.save(user); await this.cache.delete("user:" + user.id); } findAll() { return this.inner.findAll(); } async delete(id: string) { const gone = await this.inner.delete(id); if (gone) await this.cache.delete("user:" + id); return gone; }}class UserService { constructor(private users: UserRepository) {} getUser(id: string) { return this.users.findById(id); } async createUser(name: string, email: string) { if (!email.includes("@")) throw new Error("Invalid email"); const user = { id: crypto.randomUUID(), name, email }; await this.users.save(user); return user; }}const service = new UserService(new CachedUserRepository(new DatabaseUserRepository(), new InMemoryStorage()));const user = await service.createUser("Ada", "ada@example.com");console.log(await service.getUser(user.id));The same in Go
package mainimport ( "context" "encoding/json" "errors" "fmt" "strings" "sync" "time")var ErrNotFound = errors.New("not found")type Storage interface { Get(ctx context.Context, key string) ([]byte, error) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error Delete(ctx context.Context, key string) error}type entry struct { value []byte expires time.Time}type InMemoryStorage struct { mu sync.Mutex data map[string]entry}func (s *InMemoryStorage) Get(_ context.Context, key string) ([]byte, error) { s.mu.Lock() defer s.mu.Unlock() e, ok := s.data[key] if !ok || (!e.expires.IsZero() && time.Now().After(e.expires)) { delete(s.data, key) return nil, ErrNotFound } return e.value, nil}func (s *InMemoryStorage) Set(_ context.Context, key string, v []byte, ttl time.Duration) error { s.mu.Lock() defer s.mu.Unlock() e := entry{value: v} if ttl > 0 { e.expires = time.Now().Add(ttl) } s.data[key] = e return nil}func (s *InMemoryStorage) Delete(_ context.Context, key string) error { s.mu.Lock() defer s.mu.Unlock() delete(s.data, key) return nil}type User struct{ ID, Name, Email string }type UserRepository interface { FindByID(ctx context.Context, id string) (*User, error) Save(ctx context.Context, u *User) error}type DatabaseUserRepository struct{ rows map[string]User } // a real one runs SQLfunc (r *DatabaseUserRepository) FindByID(_ context.Context, id string) (*User, error) { u, ok := r.rows[id] if !ok { return nil, ErrNotFound } return &u, nil}func (r *DatabaseUserRepository) Save(_ context.Context, u *User) error { r.rows[u.ID] = *u return nil}type CachedUserRepository struct { inner UserRepository cache Storage ttl time.Duration}func (r *CachedUserRepository) FindByID(ctx context.Context, id string) (*User, error) { if b, err := r.cache.Get(ctx, "user:"+id); err == nil { var u User if json.Unmarshal(b, &u) == nil { return &u, nil } } u, err := r.inner.FindByID(ctx, id) if err != nil { return nil, err } if b, err := json.Marshal(u); err == nil { _ = r.cache.Set(ctx, "user:"+id, b, r.ttl) // a failed cache write is only a later miss } return u, nil}func (r *CachedUserRepository) Save(ctx context.Context, u *User) error { if err := r.inner.Save(ctx, u); err != nil { return err } return r.cache.Delete(ctx, "user:"+u.ID)}type UserService struct{ users UserRepository }func (s *UserService) CreateUser(ctx context.Context, id, name, email string) (*User, error) { if !strings.Contains(email, "@") { return nil, errors.New("invalid email") } u := &User{id, name, email} return u, s.users.Save(ctx, u)}func main() { ctx := context.Background() repo := &CachedUserRepository{ inner: &DatabaseUserRepository{rows: map[string]User{}}, cache: &InMemoryStorage{data: map[string]entry{}}, ttl: 5 * time.Minute, } s := &UserService{repo} u, err := s.CreateUser(ctx, "123", "Ada", "ada@example.com") fmt.Println(u, err)}The same in Java
import java.util.*;import java.util.concurrent.ConcurrentHashMap;interface Storage { Optional<Object> get(String key); void set(String key, Object value, long ttlMillis); boolean delete(String key);}class InMemoryStorage implements Storage { private record Entry(Object value, long expiresAt) {} private final Map<String, Entry> data = new ConcurrentHashMap<>(); public Optional<Object> get(String key) { Entry e = data.get(key); if (e == null) return Optional.empty(); if (System.currentTimeMillis() >= e.expiresAt()) { data.remove(key, e); return Optional.empty(); } return Optional.of(e.value()); } public void set(String key, Object value, long ttlMillis) { data.put(key, new Entry(value, System.currentTimeMillis() + ttlMillis)); } public boolean delete(String key) { return data.remove(key) != null; }}record User(String id, String name, String email) {}interface UserRepository { Optional<User> findById(String id); void save(User user); List<User> findAll();}class DatabaseUserRepository implements UserRepository { // a real one runs SQL private final Map<String, User> rows = new ConcurrentHashMap<>(); public Optional<User> findById(String id) { return Optional.ofNullable(rows.get(id)); } public void save(User user) { rows.put(user.id(), user); } public List<User> findAll() { return List.copyOf(rows.values()); }}class CachedUserRepository implements UserRepository { private final UserRepository inner; private final Storage cache; CachedUserRepository(UserRepository inner, Storage cache) { this.inner = inner; this.cache = cache; } public Optional<User> findById(String id) { Optional<Object> hit = cache.get("user:" + id); if (hit.isPresent()) return hit.map(User.class::cast); Optional<User> user = inner.findById(id); user.ifPresent(u -> cache.set("user:" + id, u, 300_000)); return user; } public void save(User user) { inner.save(user); cache.delete("user:" + user.id()); } public List<User> findAll() { return inner.findAll(); }}class UserService { private final UserRepository users; UserService(UserRepository users) { this.users = users; } Optional<User> getUser(String id) { return users.findById(id); } User createUser(String name, String email) { if (email == null || !email.contains("@")) throw new IllegalArgumentException("Invalid email"); User user = new User(UUID.randomUUID().toString(), name, email); users.save(user); return user; }}public class AbstractionLayers { public static void main(String[] args) { UserService service = new UserService( new CachedUserRepository(new DatabaseUserRepository(), new InMemoryStorage())); User user = service.createUser("Ada", "ada@example.com"); System.out.println(service.getUser(user.id())); }}