/blogs/backend-scaling-and-performance

← Back to blogs
Blog

Backend Scaling and Performance

Understanding what actually happens when a backend goes from handling hundreds of requests to handling serious traffic and how to reason about each bottleneck along the way.

·39 min read·

Backend Scaling and Performance

Scaling and performance are foundational concepts in backend engineering and infrastructure. While often used as buzzwords, they represent critical domains that dictate how systems behave under load. This discussion narrows the focus to backend systems, building an intuition for where bottlenecks hide and how to think clearly when a system begins to degrade under heavy traffic.

#Defining a "Fast" System

In modern web applications, a system is generally considered fast when user interactions yield immediate responses. When a user triggers an action such as clicking a button, a complex request lifecycle begins:

  1. Browser Action: The browser sends an HTTP request across the internet to the target application server.
  2. Server Receives Request: The application server receives and parses the incoming request.
  3. Processing & Database Interaction: The server processes the request, which typically involves interacting with a database to store or retrieve information.
  4. External API Calls: If necessary, the server communicates with external services (e.g., calling an email delivery service API like Resend).
  5. Sending the Response: The server formats a response (usually JSON) and transmits it back over the network to the browser.
  6. Browser Rendering: The browser parses the response and renders the UI updates.

The total time elapsed between the user clicking the button and the final UI rendering is referred to as latency.

Latency is the most fundamental concept in performance engineering. When users complain that an application is slow, regardless of whether they know the technical terminology, they are experiencing high latency.

#Latency is Not a Single Number

It is a common mistake to treat latency as a single, static number (e.g., "our API takes 500 milliseconds"). In real-world traffic, latency varies from request to request. One request might complete in 50ms, while another takes 200ms.

This variance occurs because network conditions and server states are rarely perfectly predictable:

  • Cache Hits vs. Database Queries: A request might be served directly from a fast, in-memory cache (like Redis) or a nearby CDN, returning in milliseconds. Another request might miss the cache and require a full database lookup, taking significantly longer.
  • Server Load and Concurrency: A request arriving when the server is idle will be processed instantly. A request arriving when the server is already processing 50 concurrent requests will be forced to wait in a queue.

The Problem with Averages

Because of this variance, average latency is largely a misleading metric for performance optimization.

Consider a scenario where 1,000 requests are measured, yielding an average latency of 100ms. However, a closer look reveals that 99% of those requests completed in under 50ms, while the remaining 1% took 5 seconds.

If this system handles 1 million requests per day, that 1% represents 10,000 requests meaning 10,000 users are staring at a loading spinner for 5 seconds. The average metric hides this severe degradation in user experience.

The Solution: Percentiles

To accurately represent performance variations, engineers rely on percentiles.

  • P50 (Median): If P50 is 400ms, 50% of users experience latency at or below 400ms.
  • P90: If P90 is 900ms, 90% of users experience 900ms or less, meaning the slowest 10% take longer than 900ms.
  • P99: If P99 is 2 seconds, 99% of users experience latency under 2 seconds, while the slowest 1% experience 2 seconds or more.
Rendering diagram...

In practice, backend engineers focus heavily on P95 and P99 latencies. The requests that fall into these upper percentiles often involve the most complex business logic such as processing payments, calling external services, or waiting for webhooks. Consequently, the users experiencing P99 latency are frequently the most valuable customers interacting with the platform.

#Throughput and Its Relationship with Latency

While latency measures the duration of an individual request, throughput measures the total volume of requests a system can handle within a given time period (e.g., Requests Per Second, or RPS).

Understanding throughput alongside latency is critical. A system might exhibit excellent latency (150ms) at 10 RPS, but if traffic spikes to 1,000 RPS, latency might suddenly skyrocket to 2 seconds.

Together, these metrics answer vital capacity questions:

  • Can the system survive a sudden traffic surge, such as a Black Friday event?
  • How many concurrent users can the system support before requiring additional infrastructure?

As throughput increases, latency does not scale linearly. Initially, latency remains relatively stable, but as the system approaches its maximum capacity, latency begins to increase dramatically.

#Utilization and the Queueing Effect

To understand why latency spikes under heavy load, it is necessary to examine utilization, the percentage of a system's capacity currently in use.

  • At 0% utilization, the system is completely idle.
  • At 100% utilization, the system is maxed out and cannot process additional work without delaying existing tasks.

When utilization is low, requests are processed immediately. However, as more requests arrive, they begin to form a queue. The CPU or worker process handles them one by one. Even if the execution rate of the worker remains constant, the perceived wait time for each request increases because it must wait for all preceding requests to finish.

The Non-Linear Reality of High Utilization

Intuitively, one might expect latency to grow linearly alongside utilization. However, as a system approaches 100% utilization, latency begins to grow exponentially.

To visualize this, consider a highway. At 50% capacity, traffic flows smoothly; cars can change lanes and maintain speed. At 80% capacity, maneuvering becomes harder, and minor slowdowns occur. At 90-100% capacity, the highway becomes highly unpredictable. A single car braking or merging creates a ripple effect, a chain reaction that causes traffic to jam completely.

At 100% utilization, the system is gridlocked. No one can move.

Rendering diagram...

The Need for Headroom

Because of this exponential relationship, systems cannot be run at 100% utilization and expected to perform reliably. Production systems typically operate at 60% to 80% utilization, reserving a 20% buffer.

This headroom is critical because real-world traffic is not perfectly linear; it arrives in bursts. Even if average traffic sits at 40% capacity, a sudden spike can instantly push utilization past 100%, causing the system to crash if no buffer exists.

#Identifying the Bottleneck

When a system is slow, it means a specific component is causing a delay. Finding this component is known as identifying the bottleneck.

A common trap in backend engineering is skipping the identification phase and immediately jumping to standard, "by-the-book" solutions:

  • Adding caching (e.g., Redis)
  • Upgrading database versions
  • Horizontally scaling servers by adding more instances

While these solutions sometimes help, they often address problems the system does not actually have. The real bottleneck remains ignored, and the system remains slow.

A Real-World Example: The Synchronous Logging Trap

Consider a GET /products/:product_id API that is performing slowly. The immediate assumption is often that the database is the culprit. In response, a development team might spend a week implementing a Redis caching layer in front of the database, only to find the API is still slow upon deployment.

The correct approach is instrumentation adding granular timing measurements across the codebase to track exactly where time is spent. Upon doing this, the team might discover:

  • The database query takes 10ms.
  • The Redis cache lookup takes 5ms.
  • A logging function takes 500ms.

The actual bottleneck was a logging function writing to a remote service like Elasticsearch. Because this operation was happening synchronously, it blocked the entire request-response cycle. The database was never the issue.

The Rule: Never guess, always measure. Without measuring each component, applying optimizations is purely speculative.

#Measuring Performance: Profiling and Tracing

To systematically identify bottlenecks, engineers rely on two primary tools: profilers and distributed tracers.

Profiling and Flame Graphs

Profiling is the practice of attaching a tool to a running application to measure exactly where it spends its time during execution. Profilers record function executions, start times, and end times.

Because profiler output can be overwhelming, engineers use Flame Graphs to visualize the data. Flame graphs display the call stack over time. Functions that take longer to execute appear wider, and functions called by other functions appear stacked on top.

Profilers are highly effective for CPU-bound tasks tasks where the CPU is the primary bottleneck due to heavy computations (e.g., sorting large datasets, image processing, or encryption).

Distributed Tracing for I/O Bound Tasks

However, most backend SaaS applications do not struggle with CPU-bound tasks; they struggle with I/O-bound tasks. These are tasks where the application spends most of its time waiting for input/output operations, such as:

  • Database queries
  • External HTTP requests
  • File system reads/writes
  • Sending emails

Standard CPU profilers are often poor at measuring I/O-bound tasks because the CPU is mostly idle during these operations, waiting on external resources.

To measure I/O bottlenecks, engineers implement distributed tracing. Tracing follows a single request as it flows through the entire system architecture, recording the exact time spent entering and exiting databases, internal functions, and external APIs. A trace might reveal that a request spent only 2ms in business logic but 800ms waiting on a database query, pinpointing exactly where optimization efforts should be focused.

#Databases as Bottlenecks

Databases are frequently the primary bottleneck in backend applications. They perform the heavy lifting of storing data durably, ensuring consistency, handling concurrent locks, and executing complex queries across massive datasets.

When optimizing database performance, there are two common "low-hanging fruits" that engineers typically investigate first: the N+1 query problem and indexing.

The N+1 Query Problem

The N+1 query problem occurs when a system fetches a list of items (1 query) and then makes an additional query for each item to fetch related data (N queries).

Imagine a blog application. To display 20 posts along with their authors' names, a frontend might call a /posts endpoint, and then loop through the 20 returned posts, calling an /users/:id endpoint for each author. This results in 21 API calls. If displaying 1,000 posts, it requires 1,001 API calls.

While this example uses frontend API calls, the N+1 problem predominantly originates at the server level specifically within how the backend communicates with the database.

The ORM Trap

Object-Relational Mappers (ORMs) often obscure the N+1 problem because they make related data access look like standard programming language constructs.

Consider this Prisma example:

>_ typescript
const posts = await prisma.post.findMany();

for (const post of posts) {
  // This executes a separate database query for EVERY post
  const author = await prisma.user.findUnique({
    where: {
      id: post.authorId,
    },
  });

  console.log({
    ...post,
    author,
  });
}

This code executes one SELECT * FROM posts query, followed by N SELECT * FROM users WHERE id = :id queries.

Every database query carries overhead: network transmission, TCP connection setup (if not pooled), query parsing, and execution planning. If 1,000 queries take 5ms each, the user waits 5 seconds just for the database interactions.

The Solution: Bulk Fetching

The solution is to instruct the ORM to fetch related data in bulk, typically translating to a SQL JOIN or a batched query under the hood.

In Prisma, this looks like:

>_ typescript
const posts = await prisma.post.findMany({
  include: {
    author: true,
  },
});

Other ORMs have equivalent primitives:

  • Django: select_related (foreign keys) or prefetch_related (many-to-many).
  • Ruby on Rails: includes.
  • Raw SQL: LEFT JOIN or INNER JOIN.

By using bulk fetching, the number of queries drops from 1,001 to exactly 2, regardless of how many items are being displayed.

The Absence of Indexes

The second major source of database latency is the absence of indexes.

Imagine a library with a million books scattered randomly across different floors and shelves, with no catalog. If a patron asks for all books by "John Green," the librarian must walk through the entire library, examining every single book. If a second patron asks the same question an hour later, the librarian must repeat the entire process.

In database terminology, this is called a sequential scan (or full table scan). The database engine must examine every single row in a table to find matching records. For large tables, this can take seconds far too slow for modern web applications.

The solution is the equivalent of a library catalog: an index.

An index is a data structure (often a B-Tree) that stores specific column values in an ordered way, along with pointers to the actual rows. When a query asks for books by "John Green," the database consults the index, instantly finds the location of all matching records, and retrieves them directly.

By analyzing application data access patterns through observability tools, engineers can identify which columns are frequently queried and add indexes to them, transforming slow sequential scans into near-instant lookups.

Mapping this back to the database context, an index is typically implemented as a B-tree data structure.

A B-tree maintains a sorted copy of a specific column's values such as an author_id along with pointers to the actual rows in the table. When a query searches for books by a specific author, the database traverses the B-tree to instantly locate the relevant pointers, bypassing the need to scan every row.

For a table with a million rows, a sequential scan might take 4 seconds to locate all records for an author. With an index in place, that same operation can complete in roughly 40 to 100 milliseconds.

The Cost of Indexes

Despite their massive performance benefits, indexes are not a free solution. They introduce two primary costs:

  1. Storage Space: An index is a separate data structure that must be stored on disk. As a table grows to millions of rows, the size of the index grows alongside it, consuming additional storage capacity.
  2. Write Overhead: This is the more problematic penalty. Every time an INSERT, UPDATE, or DELETE operation occurs on the primary table, the database must also update any associated index data structures to keep them in sync.

If a table has indexes on every single column, write operations will slow down significantly because the database must update each index one by one. This creates a severe bottleneck for write-heavy workloads.

Strategic Indexing

Because of this write penalty, engineers must be strategic when defining indexes.

  • Primary Keys: By default, databases like PostgreSQL automatically index the primary key (e.g., the id column). Explicitly indexing it is unnecessary.
  • Obvious Use Cases: If a specific data access pattern is known from the start (e.g., books will frequently be searched by author_id), an index should be created during the initial table migration.
  • Non-Obvious Use Cases: For less predictable query patterns, it is better to wait, monitor the application, and analyze observability data. Using distributed tracing, engineers can identify specific endpoints experiencing latency. If a slow query is discovered, tools like EXPLAIN ANALYZE can be used to inspect the execution plan and determine if a missing index on a column like ISBN is causing a sequential scan.

The Golden Rule of Indexing: Because of the heavy write overhead, engineers should be cautious and conservative when adding indexes, relying on measurement rather than assumption.

Advanced Indexing: Composite and Covering Indexes

As indexing strategies mature, two advanced patterns frequently emerge:

  • Composite Indexes: An index created on two or more columns (e.g., (user_id, created_at)). This optimizes queries that frequently filter by both columns. Composite indexes follow the leftmost prefix rule. An index on (A, B, C) can efficiently serve queries using A, or A+B, or A+B+C, but it cannot be used for queries starting with B or C.
  • Covering Indexes: An index that contains all the columns required to satisfy a specific query. For example, if a query only selects name and email where id = 1, an index containing id, name, and email allows the database to perform an index-only scan. It retrieves the data directly from the index without making an additional disk I/O trip to the actual table.

#The Cost of Database Connections

Once queries are optimized and indexed, the next bottleneck often lies in how the application connects to the database. In local development, database connections seem virtually free. At scale, however, they become expensive and limited resources.

When an application connects to a database, it must establish a TCP connection (requiring a three-way handshake), perform authentication, negotiate encryption (TLS), set up session state, and allocate memory on the database server. If an application opens a new connection for every single query and closes it immediately, it repeatedly pays this setup cost.

Furthermore, databases have strict connection limits. A typical Postgres instance might only support 400 to 500 concurrent connections. During a traffic spike, an application can easily exhaust this limit, causing the database to crash.

The Solution: Connection Pooling

To mitigate both the latency of connection setup and the risk of exhausting connection limits, engineers implement connection pooling.

A connection pool maintains a set of open, ready-to-use connections. When the application needs to query the database, it borrows a connection from the pool, executes the query, and returns the connection. This prevents the overhead of repeatedly establishing TCP connections.

There are two primary pooling architectures:

Rendering diagram...
  1. Internal Pooling: The database driver maintains a pool within the application server itself. While effective for a single server, this becomes dangerous during horizontal scaling. If an autoscaler adds three server instances, each maintaining a pool of 150 connections, the database receives 450 concurrent connections potentially exceeding its 300-connection limit and crashing the system.
Rendering diagram...
  1. External Pooling: A dedicated middleware component (like PgBouncer for Postgres) sits between the application servers and the database. All application instances connect to this central pooler, which maintains a strict, centralized limit on connections to the database. This acts as a gatekeeper, ensuring the database connection limit is never exceeded, regardless of how many application instances are autoscaled.

#Caching: Offloading the Database

Even with optimized queries and pooling, a database can still become a bottleneck under heavy read traffic. The next step is caching storing the results of expensive operations in a fast, in-memory data store like Redis.

If a complex database query takes 800 milliseconds to execute, caching the result allows subsequent requests to be served in 50 milliseconds.

The Challenge of Cache Invalidation

The primary difficulty with caching is invalidation ensuring the cached data does not become stale when the underlying database data changes. There are two primary techniques to handle this:

  1. Time-Based Invalidation (TTL): The cache entry is set to expire after a specific duration (e.g., 5 minutes). The challenge is determining the optimal TTL. If it is too short, the cache hit rate drops. If it is too long, the system risks serving stale data.
  2. Event-Based Invalidation: The cache is explicitly invalidated (or deleted) at the code level whenever an update operation occurs on the corresponding database record. This guarantees consistency but requires strict engineering discipline; missing a single invalidation point in the code will result in stale data.

Where Does the Cache Live?

Caches can be located in two places:

  • Local Caching: Stored in-memory within the application server (e.g., a dictionary/map). It is incredibly fast (2-3ms) but leads to cache inconsistency when multiple server instances hold different versions of the same data.
  • Distributed Caching: Stored in an external service like Redis or Memcached. All server instances share the same cache, ensuring consistency. However, it requires a network roundtrip, adding roughly 50ms of latency.

Tiered Caching combines both approaches. The "hottest" data is kept in a tiny local cache for sub-millisecond access, while the rest resides in the distributed cache.

Caching Patterns

Engineers utilize specific patterns to dictate how data flows between the application, cache, and database:

PatternHow it WorksProsCons
Cache-Aside (Lazy Loading)Application checks cache first. On a miss, it queries the DB, saves the result to the cache, and returns it.Most intuitive; prevents stale data if combined with explicit invalidation.Cache misses incur high latency.
Write-ThroughApplication writes data to the database and updates the cache simultaneously.Guarantees the cache is never stale; no cache misses for written data.Write operations take longer due to dual writes.
Write-BehindApplication writes to the cache and returns immediately. The database is updated asynchronously.Extremely fast write latency.High risk of data loss/inconsistency if the async DB write fails.

Measuring Cache Effectiveness

The effectiveness of a caching strategy is measured by the Cache Hit Rate the percentage of requests successfully served from the cache. A 90% hit rate is considered excellent. If the rate drops to 20%, it indicates a flaw in the caching strategy.

Three primary factors affect the hit rate:

  1. TTL: A longer TTL generally increases the hit rate but risks staleness.
  2. Cache Size: More memory allows more data to be stored, increasing the likelihood of hits.
  3. Data Access Patterns: A deep understanding of which endpoints are accessed most frequently is critical. Without aligning the caching strategy with actual user behavior, the hit rate will suffer.

#Scaling: Vertical vs. Horizontal

Once an application is fully optimized queries are indexed, connections are pooled, and caching is implemented the next question is how to handle raw capacity growth. There are two fundamental approaches to scaling infrastructure.

Vertical Scaling (Scaling Up)

Vertical scaling involves replacing an existing server with a more powerful one. This is achieved by upgrading hardware: adding more CPU cores, increasing RAM, expanding storage (e.g., moving to NVMe SSDs), or upgrading network cards.

The Advantages:

  • Simplicity: The system architecture remains unchanged. No code modifications are needed to handle distributed state.
  • Economics: A server with twice the processing power typically costs less than two smaller servers combined. It avoids the operational overhead of managing multiple machines, load balancers, and backups.

The Disadvantages:

  1. Hard Limits: There is a physical ceiling to hardware. Once an application outgrows the largest instance size offered by a cloud provider, vertical scaling stops.
  2. Single Point of Failure (SPOF): One powerful server means one point of failure. If it crashes, the entire application goes down.
  3. No Geographic Distribution: A single server in the USA cannot physically reduce latency for users located in India.

Horizontal Scaling (Scaling Out)

Horizontal scaling takes a different approach. Instead of buying a bigger server, engineers add more servers of the same size. Multiple medium-powered machines work together behind a load balancer to serve traffic.

The Advantages:

  • Theoretical Infinite Scalability: If one server handles 1,000 RPS, five servers handle 5,000 RPS. Capacity can be increased simply by adding more instances.
  • Redundancy: If one server fails, traffic is automatically routed to the remaining healthy instances, ensuring high availability.
  • Geographic Distribution: Instances can be deployed in data centers around the world, routing user requests to the nearest server to minimize latency.
Rendering diagram...

The Disadvantages (Complexity):

Horizontal scaling does not eliminate problems; it transforms them into a different set of distributed systems problems:

  1. Load Balancing: A new component must be introduced to distribute traffic evenly, requiring decisions about load balancing algorithms.
  2. State Management: If a user updates their profile on Server 1, Server 2 must be made aware of this change. This necessitates moving local state (like session data or file uploads) to shared external stores (e.g., Redis or S3).
  3. Network Partitions (Split-Brain): If the network connecting the servers fails, instances may become isolated and start making conflicting decisions, leading to data inconsistency.
  4. Health Checks and Recovery: Infrastructure must be configured to continuously monitor server health, reroute traffic away from dead instances, and seamlessly integrate them back when they recover.

Ultimately, the choice between vertical and horizontal scaling is a trade-off. Teams must decide whether they want to deal with the hard limits of single-machine hardware or the architectural complexity of distributed systems.

Horizontal scaling requires planning the entire stack from the ground up. Unlike vertical scaling, which simply involves allocating more CPU or memory to an existing machine, horizontal scaling demands architectural changes to both code and infrastructure. The core principle that makes this possible is statelessness.

The Key Enabler: Statelessness

When multiple instances of a backend application run simultaneously, incoming internet traffic is distributed across them. Statelessness dictates that no single server instance holds exclusive data. If Instance D holds data that Instance A or C cannot access, the horizontal scaling setup fails.

If a user’s request hits Instance A on the first cycle and Instance B on the second, Instance B must have the exact same contextual understanding as Instance A. If Instance B lacks the necessary state, it throws an error.

To achieve this, instances must not hold any information locally. If data must persist, it must live in a centralized location accessible by all instances.

Session Management

Consider a typical authentication flow. A user submits credentials, the server validates them, creates a session, and stores the session ID in the user's browser cookies. In a stateful architecture, the server also saves session data in its own local memory.

In a horizontally scaled environment with instances A, B, and C, if the user authenticates against Instance A, Instance A stores the session in its local memory. When the subsequent request routes to Instance B, Instance B cannot access Instance A's memory. The user receives a 401 Unauthorized error and is forced to authenticate again.

The stateless solution externalizes session storage. Instead of local memory, Instance A writes the session to an in-memory datastore like Redis. When the next request hits Instance B, Instance B queries the shared Redis instance, validates the session, and processes the request successfully.

File Storage

The same pattern applies to file storage. If a user uploads a file to Instance A, and Instance A saves it to its local SSD, a subsequent request to read that file routed to Instance C will fail.

Instead of local storage, files must be uploaded to centralized object storage such as AWS S3, Cloudflare R2, or a self-hosted MinIO instance. All backend instances interact with the centralized storage layer, ensuring any instance can retrieve the file.

The fundamental rule is to externalize everything. Databases must be centralized (e.g., Postgres or a managed RDS instance) rather than stored locally on the server (like SQLite).

Load Balancers

Once an application is stateless and multiple instances are running, a mechanism is required to distribute incoming traffic. A Load Balancer (LB) sits at the entry point of the infrastructure, acting as a middleman between the internet and the server instances.

The load balancer receives all client requests, forwards them to a specific server instance based on a routing algorithm, receives the server's response, and returns it to the client over the same HTTP connection.

Load Balancing Algorithms

The logic a load balancer uses to route traffic dictates system performance under varying loads.

Round Robin The simplest approach. The load balancer maintains a rotating list of servers. Request 1 goes to A, 2 to B, 3 to C, 4 goes back to A, and so on. This works well when all requests require roughly the same processing power and all instances have identical hardware specifications.

The Problem with Simple Round Robin In real-world scenarios, request costs vary. A SELECT query might take 200 milliseconds, while a complex request involving an external HTTP call and a database write operation with heavy indexing might take 2 seconds. If traffic skews toward expensive requests, Round Robin mindlessly distributes them evenly. A single server might receive multiple expensive requests in sequence, causing resource exhaustion and crashing the instance.

Weighted Round Robin If Instance A has 8 GB of RAM and 4 CPU cores, while Instances B and C have 4 GB of RAM and 2 CPU cores, a Weighted Round Robin configuration sends twice as many requests to Instance A, utilizing its higher capacity. However, it still cannot differentiate between lightweight and expensive requests.

Least Connections This algorithm routes traffic based on active connections. When a client sends a request, the HTTP/TCP connection remains active while the server processes the logic, makes external API calls, or waits for database writes.

The load balancer tracks these active connections. If Instance A is currently processing a heavy 2-second request, its active connection count is 1. If a new lightweight request arrives, the load balancer sees that Instances B and C have 0 active connections and routes the request there.

Variations of this include Weighted Least Connections (accounting for hardware specs) and Least Response Time (routing to the server returning responses the fastest).

Rendering diagram...

Health Checks

If a server instance crashes, a load balancer using Round Robin or Least Connections will continue forwarding traffic to the dead machine. Users hitting that specific instance receive 502 or 503 errors.

To mitigate this, load balancers implement health checks. The load balancer routinely sends a lightweight test request (e.g., a GET /health endpoint) to every instance.

If an instance returns a 200 response, it is considered healthy. If it returns an error or times out, the load balancer instantly blacklists the instance. No user traffic is routed to the blacklisted server. The load balancer continues sending health checks to the dead instance; once it recovers and returns a 200, it is removed from the blacklist and begins receiving traffic again.

Scaling Stateful Databases

Application servers scale easily once state is externalized. However, the externalized state itself specifically, the database becomes the bottleneck. Databases cannot be duplicated as trivially as stateless application servers because they hold massive amounts of data that must remain consistent across all instances.

Read Replicas

Most SaaS applications experience a heavily read-dominated workload, often averaging a 70% read and 30% write split. Read replicas exploit this pattern.

A primary database instance handles all write operations (INSERT, UPDATE, DELETE). Secondary instances, called read replicas, synchronize with the primary instance and handle all read operations (SELECT).

Rendering diagram...

This architecture provides two major benefits:

  1. Reduced Load: The primary database only handles 30% of the overall traffic.
  2. Lower Latency: Replicas can be geographically distributed. A user in India can read from a local replica rather than querying a primary database in the US.

The Replication Lag Trade-off

Consistency is the primary challenge with read replicas. Data replication is not instantaneous; it is bound by physics.

If a user in India updates their profile name, the write hits the primary database in the US. The user's frontend immediately issues a GET request to fetch the updated profile. Because this is a read operation, it routes to the read replica in India.

However, the data has not yet traveled from the US to India. The replication lag might be 200 milliseconds. The read replica returns the stale, pre-update data.

Solutions to this consistency issue include:

  • Intelligent Routing: Temporarily routing read requests for a specific user to the primary database immediately following a write operation.
  • Lag Tracking: Blocking read queries until the replication lag drops to zero.
  • Frontend Latency: Introducing a planned delay on the client side before issuing the subsequent GET request.

Database Sharding

When datasets grow to billions of rows, query latency degrades even with indexes. A single database instance cannot handle the storage or throughput requirements.

Sharding (or horizontal partitioning) splits a massive table across multiple database instances. For example, an orders table can be split using a sharding key like order_date:

  • Instance 1: Holds orders from January to June.
  • Instance 2: Holds orders from July to December.

This reduces the dataset size per instance, lowering query latency, and increases overall throughput since multiple instances handle the request volume.

Modern distributed databases like PlanetScale (using Vitess), CockroachDB, or Yugabyte handle sharding, replication, and distributed transactions automatically. Engineers typically consume these as managed services rather than building the infrastructure from scratch.

Global Caching and CDNs

Even with highly optimized backend infrastructure, physical distance dictates latency. Data travels through fiber optic cables at approximately 200,000 kilometers per second. A round-trip request from Tokyo to a server in Virginia covers roughly 20,000 km, establishing a hard physics limit of 100 milliseconds just for network transit.

Once the request reaches the server, routing, JSON deserialization, database queries, and potential external API calls add another 400 to 700 milliseconds. The user experiences 500 to 800 milliseconds of total latency.

Points of Presence (PoPs)

Content Delivery Networks (CDNs) solve the physics problem by placing caching servers, known as Points of Presence (PoPs) or edge locations, geographically close to users.

If a user in Tokyo requests a resource, the request hits a CDN node in Tokyo rather than traveling to Virginia. The round-trip distance shrinks to 100-200 km, dropping network latency from 100 milliseconds to roughly 2-3 milliseconds.

CDNs cache static content like JavaScript bundles, CSS, HTML, images, and videos. They can also cache API responses, such as an e-commerce product catalog, using cache purge tags to invalidate stale data when updates occur.

Beyond performance, CDNs provide security. By absorbing traffic at edge locations, CDNs mitigate DDoS attacks. Providers like Cloudflare distribute malicious traffic across a massive global network, preventing it from overwhelming the primary origin servers.

The Evolution to Edge Computing

Traditional CDNs operate as simple file stores. A user requests a specific file, the CDN finds it, and returns it. No complex processing occurs.

Edge computing shifts lightweight processing to the CDN layer.

Consider an authentication request. A user in Tokyo sends a session cookie to a server in Virginia. The server checks Redis, determines the session is invalid, and returns a 401 Unauthorized response. This failure cycle cost 100 milliseconds of network latency.

With edge computing, the authentication check executes directly on the CDN node in Tokyo. If the session is invalid, the edge node returns a 401 in 2-3 milliseconds. The primary server in Virginia is never disturbed by unauthorized traffic.

Edge nodes excel at localization. An edge node can inspect browser headers and instantly serve a localized Japanese version of a website without querying a central database.

Edge Constraints

Edge computing cannot replace primary data centers. Edge nodes operate within ISP infrastructure, which prioritizes routing over computation. They have limited hardware (often 1 GB of RAM and single-core CPUs) and strict runtime constraints. Platforms like Cloudflare Workers use V8 isolates, which prevent interaction with the local file system or raw TCP protocols.

Because of these constraints, heavy business logic and complex database transactions remain on robust primary servers. Edge nodes handle targeted, lightweight logic failing fast on invalid requests, applying localization, and routing traffic working in tandem with the primary infrastructure.

While offloading lightweight logic to edge nodes reduces latency for simple checks, more complex operations often require a different approach to avoid blocking the primary request-response cycle. This is where asynchronous processing becomes critical.

Introduction to Asynchronous Processing

Reducing backend latency or at least reducing the perceived latency from the user's perspective often relies on asynchronous processing. Unlike horizontal scaling, which is typically implemented after hitting specific traffic thresholds, asynchronous processing is usually adopted at the very beginning of an application's lifecycle.

In a standard synchronous flow, a client sends a request, the server processes it, interacts with the database, and only returns a response once the operation is fully complete. If a user updates their profile name, the server executes the database update, waits for confirmation, and then sends a 200 OK response. The user needs to see this change immediately upon refreshing, making it a synchronous operation.

However, many operations do not require immediate execution or visibility.

The Workspace Invite Flow

Consider a workspace invitation flow in a SaaS application. A user enters an email address and clicks "Invite." The backend processing looks like this:

  1. Validation: The server queries the database to check if the invited user is already part of the team.
  2. Database Save: If validation passes, the server inserts a record into an invites table with a pending status.
  3. Email Notification: The server triggers an external API call to an email provider (like SendGrid or Resend) to deliver the invitation.

The Synchronous Bottleneck

Steps 1 and 2 are fast, typically taking 50 to 100 milliseconds since the database is usually in the same data center. Step 3, however, involves an external HTTP call to a third-party email provider. This call can take an additional 200 to 300 milliseconds.

If handled synchronously, the user stares at a loading spinner for roughly 400 milliseconds before seeing a success message.

The Asynchronous Solution

To reduce perceived latency, the server can execute steps 1 and 2, push the email task to a background queue, and immediately return a 200 OK response to the user. The UI updates to show the invitation in a pending state. The user interaction drops from 400 milliseconds to 100 milliseconds. The actual email sending happens out-of-band, and since users do not expect the email to arrive in the exact millisecond they click "Invite," the user experience remains intact.

Implementing Asynchronous Processing with Message Queues

Asynchronous processing is typically implemented using a message queue. Instead of executing the task immediately, the server (acting as a producer) pushes a job or task to a queue.

Common queue technologies include:

  • Redis Queues (often using libraries like BullMQ in Node.js)
  • RabbitMQ
  • Kafka (for event-driven architectures)

A separate process, known as a consumer or worker, listens to the queue. The worker picks up the task and executes the heavy logic such as making the external API call to the email provider.

Rendering diagram...

Workers can run within the same codebase as the main server or as a completely separate deployment. Separating them allows the worker tier to be horizontally scaled independently, which is useful if email sending becomes a bottleneck.

Ideal Use Cases for Asynchronous Processing

Any task where the user does not expect an immediate result is a candidate for asynchronous processing.

  • Video Processing: When a user uploads a video to a platform like YouTube, the upload itself is synchronous. However, generating thumbnails, encoding the video into different resolutions (HD, 4K), and generating subtitles are pushed to a background queue. The user can close the tab, and the platform processes these tasks over several minutes.
  • Account Deletion: Deleting a user account often requires cascading deletes across multiple database tables (todos, schedules, profile data, preferences). If a user has thousands of rows, running these deletes synchronously could take 8 seconds or more, resulting in a terrible user experience and potential database lock contention. Instead, the server verifies the user's credentials, immediately logs them out, and pushes a delete_user task to the queue. A worker executes the cascading deletes in the background, taking however long is necessary without blocking the user.

The Trade-offs of Microservices

Asynchronous processing introduces distributed components (workers, queues). This hints at a broader architectural pattern: microservices. While microservices offer organizational and scaling benefits, they introduce significant complexity.

  1. Network Overhead: In a monolith, calling a function is instantaneous. In a microservices architecture, a single user request might flow through an API Gateway, an Order Service, a Payment Service, and a Notification Service. Each interaction is now a network call (HTTP or gRPC), introducing latency and the potential for network failures. Engineers must implement retries, timeouts, and circuit breakers.
  2. Debugging Complexity: Debugging a monolith involves reading a single log file. Debugging a distributed request across four microservices requires distributed tracing tools (like Jaeger or Datadog) to correlate logs and identify where a request failed.
  3. Data Consistency: Each microservice typically owns its database. Maintaining consistency across these databases introduces replication lag and distributed transaction challenges (often requiring patterns like Saga or Two-Phase Commit).

Microservices are typically only justified when an organization has large teams that need clear boundaries, or when specific parts of the system require independent scaling or different technology stacks. For most applications, a well-structured monolith remains the simpler, more efficient choice.

Introduction to Serverless Computing

Serverless computing has emerged as a modern approach to scaling backend applications, popularized by platforms like AWS Lambda, Vercel, and Cloudflare Workers.

The Traditional "Serverful" Model

Traditionally, backend applications run on Virtual Machines (VMs) provisioned from cloud providers. Engineers select an operating system, install dependencies, configure web servers (like Nginx), deploy the application, and manage it continuously.

This model requires capacity planning. Engineers must predict traffic before deployment.

  • Underprovisioning: If traffic spikes and the server lacks resources, the application becomes unresponsive or crashes.
  • Overprovisioning: If the server is too powerful, the organization pays for unused capacity 24/7.

Autoscaling mitigates this by spinning up new instances when CPU or memory crosses a threshold (e.g., 70%). However, autoscaling is reactive. It takes time to boot an OS, fetch code, and start the application. If a traffic spike happens in seconds, the autoscaler may be too slow, leading to crashes. Furthermore, there is always an "always-on" cost for the minimum number of instances running.

The Serverless Model

Serverless abstracts the underlying machines away. Developers do not manage operating systems or VMs. They only manage functions pieces of code triggered by events (like an HTTP request).

An API Gateway sits in front of the functions. When a request arrives, the gateway routes it to the appropriate function. The serverless provider (e.g., AWS) dynamically provisions a compute instance, runs the code, returns the response, and then tears down or freezes the instance.

The pricing model changes fundamentally: instead of paying for a server 24/7, organizations pay only for the milliseconds of CPU time their code actually executes.

The Catch: Serverless Trade-offs

Serverless is not a silver bullet and comes with distinct limitations.

  • Cold Starts: If a function has not been invoked recently, the provider must provision a new instance. This "cold start" introduces latency. Booting an OS/VM and initializing a language runtime (like Java's JVM) takes time. Platforms like AWS Lambda use Firecracker microVMs to reduce boot times, while Cloudflare Workers use V8 isolates to achieve near-zero cold starts (around 5 milliseconds). However, cold starts are an inherent trade-off of the architecture.
  • Execution Limits: Serverless functions have strict timeout limits. AWS Lambda, for example, caps execution at 15 minutes. Long-running processes (like prolonged WebSocket connections or massive data processing) are not suitable.
  • Strict Statelessness: Because instances are ephemeral, serverless functions must be completely stateless. Maintaining persistent TCP connections to databases or holding in-memory state between requests is not feasible without external services (like a serverless database or Redis).

Serverless excels for event-driven workloads, image resizing, video processing triggers, or intermittent tasks where paying for idle servers is wasteful. It is poorly suited for latency-sensitive applications like banking or high-throughput, constant-load APIs.

Key Takeaways on Scaling and Performance

Scaling and performance optimization are governed by a few core engineering principles.

Rule 1: Always Start with a Problem

Premature optimization is a common pitfall. Before implementing caching, sharding, or microservices, engineers must measure the system to identify actual bottlenecks. Observability tools logs, metrics, and traces (using Prometheus, Grafana, or managed APMs like New Relic)are mandatory. If the database is slow, is it missing an index? Is it lacking sharding? Measuring provides the specific answer required to select the right solution.

Rule 2: Always Prefer Simple Solutions

Complexity has a cost. A monolith is simpler to debug and operate than microservices. Adding a database index is simpler than introducing a Redis caching layer. Vertical scaling is simpler than building a horizontally scalable, stateless architecture. Complexity should only be accepted when simplicity is genuinely insufficient.

Rule 3: Scale for the Problems You Have

Building a system for millions of users on day one is rarely necessary. Applications should be built for current scale with reasonable headroom. Generic architecture blogs from massive tech companies do not necessarily apply to smaller systems. Letting the system struggle under real load reveals exactly where the bottlenecks lie, allowing for targeted scaling.

Rule 4: Observability from Day One

While favoring simple solutions, observability is an exception that must be implemented from the start. Without metrics, logs, and traces, engineers operate blind. Proper observability provides early warnings before crashes occur and makes diagnosing issues trivial.

Rule 5: It’s a Mindset

Performance engineering is an ongoing discipline. Systems evolve, traffic patterns shift, and new bottlenecks emerge. The goal is not to predict every failure, but to build systems that fail gracefully and to develop the diagnostic skills to resolve issues rapidly when they occur.

7,359 words left