Sign in

Basic system components: understanding clients, servers, databases, and caches

Learn how frontends, backends, databases, caches, and APIs interact to form reliable, scalable software architectures.

MonksBit Desk

November 21, 2026 · 8 min read · 30 views

Read

A software system is a network of discrete components that collaborate to solve user requests. The core components consist of the client-facing frontend, the compute-oriented backend, persistent database storage, temporary low-latency cache memory, and the Application Programming Interfaces (APIs) that regulate communication between them.

You will need. Basic knowledge of client-server terminology · Familiarity with foundational programming in Python

How well do you know this already?

The full lesson

Level 1 · Beginner: Foundational roles of system components

Software architecture separates concerns across different components. The frontend represents the presentation layer that captures user interaction and displays output. The backend runs business logic and enforces data rules. The database retains durable records even when programs restart.

An Application Programming Interface (API) is a formal contract of endpoints, data schemas, and methods through which the frontend and backend talk to each other without exposing inner implementation details. A cache provides high-speed, volatile storage to serve repetitive queries without loading the underlying database.

Imagine a user viewing their profile balance. The frontend sends an HTTP GET request over the network. The backend receives the request, inspects a fast cache first, falls back to querying the database on a cache miss, populates the cache for future queries, and returns the balance in a structured payload such as JSON back to the client.

A minimal model simulating frontend, backend, cache, and database coordination

class Database:    def __init__(self):        self._records = {"user_1": {"name": "Alice", "balance": 100}}    def read(self, user_id):        return self._records.get(user_id)class Cache:    def __init__(self):        self._storage = {}    def get(self, key):        return self._storage.get(key)    def set(self, key, value):        self._storage[key] = valueclass BackendService:    def __init__(self, db, cache):        self.db = db        self.cache = cache    def get_user_profile(self, user_id):        cached = self.cache.get(user_id)        if cached is not None:            return {"data": cached, "source": "cache"}        record = self.db.read(user_id)        if record:            self.cache.set(user_id, record)            return {"data": record, "source": "database"}        return {"error": "Not Found", "source": "database"}db = Database()cache = Cache()api = BackendService(db, cache)# Frontend invocation simulationsprint(api.get_user_profile("user_1"))print(api.get_user_profile("user_1"))

Key takeaways

  • The frontend handles presentation while the backend enforces validation and logic.
  • The database provides durable state, and the cache provides low-latency temporary reads.
  • APIs define explicit communication protocols between separated layers.

Level 2 · Intermediate: Designing resilient APIs and caching layers

In production systems, components do not sit in the same memory space; they communicate across unreliable networks. A robust backend must handle cache misses, concurrent updates, validation errors, and cache invalidation when state modifications occur.

A standard read pattern is Cache-Aside (Lazy Loading): the application queries the cache first. Upon a cache miss, it reads from the database, writes the item to the cache with an optional Time-To-Live (TTL), and returns the payload. During writes, the application must update or delete the cached entry to prevent stale reads.

The code below demonstrates a concrete backend controller managing both read and write API endpoints with input validation, cache invalidation, and mock persistence.

Production-pattern API controller with cache-aside read and invalidation on write

import timefrom typing import Optional, Dict, Anyclass KeyValueStore:    def __init__(self):        self._data: Dict[str, Dict[str, Any]] = {}    def fetch(self, key: str) -> Optional[Dict[str, Any]]:        return self._data.get(key)    def persist(self, key: str, value: Dict[str, Any]) -> None:        self._data[key] = value.copy()class InMemoryCache:    def __init__(self, default_ttl_sec: float = 60.0):        self._entries: Dict[str, tuple[Dict[str, Any], float]] = {}        self.default_ttl = default_ttl_sec    def get(self, key: str) -> Optional[Dict[str, Any]]:        entry = self._entries.get(key)        if not entry:            return None        data, expires_at = entry        if time.time() > expires_at:            del self._entries[key]            return None        return data    def put(self, key: str, value: Dict[str, Any]) -> None:        expires_at = time.time() + self.default_ttl        self._entries[key] = (value.copy(), expires_at)    def invalidate(self, key: str) -> None:        self._entries.pop(key, None)class UserApiController:    def __init__(self, db: KeyValueStore, cache: InMemoryCache):        self.db = db        self.cache = cache    def handle_get(self, user_id: str) -> Dict[str, Any]:        if not user_id:            return {"status": 400, "body": {"error": "Missing user_id"}}        cached_user = self.cache.get(user_id)        if cached_user is not None:            return {"status": 200, "body": cached_user, "source": "cache"}        user = self.db.fetch(user_id)        if user is None:            return {"status": 404, "body": {"error": "User not found"}}        self.cache.put(user_id, user)        return {"status": 200, "body": user, "source": "database"}    def handle_put(self, user_id: str, payload: Dict[str, Any]) -> Dict[str, Any]:        if not user_id or "balance" not in payload:            return {"status": 400, "body": {"error": "Invalid payload"}}        self.db.persist(user_id, payload)        self.cache.invalidate(user_id)        return {"status": 200, "body": {"updated": True}}# Verificationdb = KeyValueStore()cache = InMemoryCache(default_ttl_sec=10.0)api = UserApiController(db, cache)api.handle_put("u123", {"name": "Bob", "balance": 250})res1 = api.handle_get("u123")  # Fetched from DBres2 = api.handle_get("u123")  # Fetched from Cacheapi.handle_put("u123", {"name": "Bob", "balance": 300})res3 = api.handle_get("u123")  # Fetched from DB after invalidationassert res1["source"] == "database"assert res2["source"] == "cache"assert res3["source"] == "database" and res3["body"]["balance"] == 300

Key takeaways

  • Cache-Aside pattern offloads database reads by loading and populating data on demand.
  • Mutations require prompt cache invalidation or updating to avoid serving stale data.
  • APIs must communicate failure conditions with explicit status codes and error payloads.

Level 3 · Advanced: Mitigating failure modes and scaling component boundaries

In high-throughput systems, naive interactions between components introduce catastrophic vulnerabilities: cache stampede (thundering herd), cache penetration, and cache breakdown.

A cache stampede occurs when an intensely accessed key expires, causing thousands of concurrent backend threads to hit the persistent database simultaneously. Cache penetration happens when queries for non-existent keys repeatedly miss both cache and database, overloading the storage engine. Systems mitigate this using Bloom filters or caching null results with brief TTLs.

To prevent cache stampedes, systems introduce mutex locking or probabilistic early expiration (such as the XFetch algorithm), which recomputes data in the background before the key fully expires. System architects also implement circuit breakers at API boundaries to gracefully degrade backend services when dependent databases stall or fail entirely.

Single-flight cache query coordinator preventing cache stampedes

import threadingfrom typing import Callable, Any, Dictclass SingleFlightCoordinator:    def __init__(self):        self._lock = threading.Lock()        self._calls: Dict[str, threading.Event] = {}        self._results: Dict[str, Any] = {}    def execute(self, key: str, query_fn: Callable[[], Any]) -> Any:        with self._lock:            if key in self._calls:                event = self._calls[key]                execute_work = False            else:                event = threading.Event()                self._calls[key] = event                execute_work = True        if execute_work:            try:                result = query_fn()                self._results[key] = result            finally:                event.set()                with self._lock:                    del self._calls[key]            return result        else:            event.wait()            return self._results.get(key)

Key takeaways

  • Cache stampedes occur when heavily requested keys expire, overwhelming the database.
  • Single-flight request deduplication consolidates identical concurrent fetches into a single database hit.
  • Resilient system design requires circuit breakers and rate limiters at API component boundaries.

Complexity

  • Time: Cache lookups: O(1) average; Database indexed lookups: O(log N) or O(1) depending on storage engine.
  • Space: O(M + N) where M is the working set stored in memory cache and N is total durable state stored in the database.

Hash-table-based caches provide constant-time key lookups, while persistent relational databases or document stores use B-Trees with logarithmic query cost or LSM-trees. Memory space is bounded by the cache eviction policy (such as LRU), while database storage scales linearly with total historical and domain data.

Common mistakes

  • Treating the cache as the source of truth, causing silent data loss during node restarts.
  • Failing to implement cache invalidation during write operations, causing users to see stale data.
  • Not setting a Time-To-Live (TTL) on cached records, resulting in memory exhaustion.
  • Coupling the frontend directly to the database without an intermediary API layer to enforce security and business rules.

Practice problems

  1. Implement Least Recently Used (LRU) Cache Eviction (easy). Hint: Use a combination of a hash map and a doubly linked list to achieve constant-time lookup and eviction.
  2. Build Cache-Aside with Null-Object Caching (medium). Hint: Store a special sentinel value with a short TTL when the database returns no row, preventing repeat penetration queries.
  3. Design Write-Through Caching with Distributed Fallback (hard). Hint: Ensure the database and cache write within a coordinated transaction or compensational rollback if one storage layer fails.

Summary

Basic software architectures rely on distinct responsibilities: frontends present interfaces, APIs dictate protocols, backends enforce validation and business logic, caches minimize access latency, and databases guarantee durability. Understanding the contracts and failure modes between these tiers enables developers to design scalable, fault-tolerant software systems.

Finish the Prove step above to complete this lesson.

Was this helpful?

Comments (0)

Sign in or create an account to join the conversation.

  • No comments yet. Be the first!