SiteTidy
HomeGuidesBuilding Scalable REST APIs (Part 2): Make the Data Path Scale
Backend

Building Scalable REST APIs (Part 2): Make the Data Path Scale

Scale REST API data access with bounded queries, indexes, keyset pagination, projections, connection pools, read models and evidence-led caching.

Published on August 15, 2026Updated August 31, 2026
Building Scalable REST APIs (Part 2): Make the Data Path Scale

Most APIs do not become slow because JSON serialization suddenly stopped scaling. They become slow because a cheap-looking endpoint quietly turns into an expensive data operation.

One request becomes twelve queries. A list endpoint starts scanning millions of rows. Every response calculates an exact count. A connection pool is exhausted while threads wait on slow SQL. Then somebody adds Redis in front of the problem and calls it fixed.

Part 1 established the HTTP contract. This part follows a request through the data path and asks a more useful question: how much work does one API request force the system to do as the dataset and traffic grow?

Start with a request budget

Take an endpoint such as:

GET /customers/42/orders?limit=50

Its latency is not one thing. It may include:

network -> gateway -> authentication -> application -> connection wait
        -> database query -> dependent queries -> mapping -> serialization
        -> network

If p95 latency is 900 ms, “the API is slow” tells you almost nothing.

Measure the components separately. At minimum, useful production telemetry should let you correlate an HTTP request with:

  • database duration;
  • number of database calls;
  • rows read/returned where practical;
  • external dependency duration;
  • cache hits/misses;
  • connection-pool waits;
  • queue or thread-pool pressure;
  • response size.

Optimise the dominant cost, not the most fashionable layer.

Bounded work is the central scaling rule

The safest endpoints have a ceiling on how much work one request can trigger.

Unbounded collection endpoints violate that rule immediately:

SELECT * FROM Orders ORDER BY CreatedAt DESC;

The query may look fine with 8,000 rows and become absurd with 80 million.

Put limits in the public contract and enforce a server-side maximum even if the caller requests more:

GET /orders?limit=50
var limit = Math.Clamp(requestedLimit ?? 50, 1, 200);

The same principle applies beyond pagination. Bound:

  • uploaded body size;
  • batch size;
  • date ranges;
  • search complexity;
  • graph depth;
  • export size;
  • concurrency per tenant;
  • expensive downstream fan-out.

A request that can cause unlimited work is a scalability problem and often a security problem too.

Index for the query you actually run

An index is not a generic “make SQL fast” switch.

Suppose the endpoint is:

GET /customers/42/orders?status=open&limit=50

and its query is conceptually:

SELECT TOP (@Limit)
    Id,
    CustomerId,
    Status,
    CreatedAt,
    Total
FROM Orders
WHERE CustomerId = @CustomerId
  AND Status = @Status
ORDER BY CreatedAt DESC, Id DESC;

An index beginning with columns that support the filtering and ordering may transform the operation. The exact index depends on your database, data distribution, selectivity, included columns and write workload.

The important habit is to inspect the actual execution plan and production-shaped data rather than guessing.

Too many indexes have a cost

Indexes consume storage and make writes more expensive. Every insert/update may have more structures to maintain.

Design them around important access patterns, then measure.

Select only the data the response needs

This is wasteful:

SELECT * FROM Customers WHERE Id = @Id;

when the API returns:

{
  "id": "42",
  "displayName": "Northwind",
  "email": "hello@example.com"
}

Projection reduces database I/O, network transfer, mapping work and the chance of accidentally exposing a newly added internal column.

SELECT Id, DisplayName, Email
FROM Customers
WHERE Id = @Id;

This matters even more on list endpoints.

Watch for N+1 queries

N+1 is one of the easiest ways to make an endpoint look fine in development and collapse under real data.

Imagine loading 50 orders and then lazily loading each customer’s name:

1 query for orders
50 queries for customers

One HTTP request just generated 51 database round trips.

Fixes depend on the use case:

  • join when the relationship is appropriate;
  • fetch related rows in a bounded second query;
  • project directly into a read DTO;
  • batch IDs;
  • use a dedicated read model for frequently requested aggregate views.

Do not blindly include an entire object graph either. Replacing 51 small queries with one enormous Cartesian explosion is not a victory.

Offset pagination has a scaling limit

Offset pagination is convenient:

ORDER BY CreatedAt DESC
OFFSET 500000 ROWS FETCH NEXT 50 ROWS ONLY;

The database still has to locate/order/skip the preceding result set. Deep offsets can become expensive, and concurrent inserts can cause clients to see duplicates or miss rows between pages.

For feeds, event streams and large operational tables, keyset/cursor pagination is often a better fit.

Given an ordering:

ORDER BY CreatedAt DESC, Id DESC

the next page can continue from the final tuple:

WHERE
    CreatedAt < @LastCreatedAt
    OR (CreatedAt = @LastCreatedAt AND Id < @LastId)
ORDER BY CreatedAt DESC, Id DESC

The cursor can encode those values rather than exposing implementation detail directly.

A cursor is not automatically secure

If it contains state the client must not tamper with, sign it or otherwise protect its integrity. If it contains sensitive information, encoding it as Base64 does not make it secret.

Keep cursor contents minimal.

Exact counts can dominate list requests

A common pattern is:

SELECT ... -- page query
SELECT COUNT(*) ... -- total count

The first query returns 50 indexed rows in milliseconds. The second scans or evaluates a huge filtered population just so the UI can say “Page 1 of 182,473”.

Ask whether the product genuinely needs an exact total.

Alternatives include:

  • hasMore;
  • approximate counts;
  • counts computed separately;
  • cached summary statistics;
  • no count at all.

The fastest query is often the one the contract stops requiring.

Connection pools are finite

Opening a brand-new physical database connection for every request is expensive, so database clients normally pool them.

That does not make connections infinite.

If the application has a pool of 100 usable connections and slow queries hold each one for several seconds, request concurrency can exhaust the pool. New requests then wait even if the application server has plenty of CPU.

Increasing the pool to 1,000 may simply move the overload into the database.

Treat connection occupancy as a scarce resource:

await using var connection = dataSource.CreateConnection();
await connection.OpenAsync(cancellationToken);

// Do the bounded database work.

Open late, release early, and do not hold a connection while waiting on unrelated HTTP calls or long-running application work.

Propagate cancellation

When a client disconnects or a request deadline expires, work that no longer has a consumer should stop where practical.

In ASP.NET Core, for example, propagate the request cancellation token into asynchronous database and dependency calls:

var customer = await repository.GetCustomerAsync(
    id,
    HttpContext.RequestAborted);

Cancellation is not magic; the underlying operation must support it. But allowing abandoned expensive queries to run to completion wastes capacity precisely when a system is under pressure.

Async helps concurrency, not query efficiency

await does not make a 4-second query fast.

Asynchronous I/O lets a server avoid occupying a thread while waiting on I/O, which can improve concurrency. It does not reduce database CPU, rows scanned or downstream latency.

You still have to fix the expensive operation.

This distinction prevents a lot of misleading performance work.

Avoid request-time fan-out when you can

An endpoint that calls five services serially inherits all five latencies:

API -> customer service -> billing -> inventory -> recommendations -> shipping

Parallelising independent calls can reduce elapsed time, but it increases concurrent downstream load and does not remove failure coupling.

Ask whether the endpoint really needs five live dependencies.

For read-heavy composite views, a denormalised read model can be more resilient:

Domain events -> projection worker -> CustomerDashboardReadModel
                                     ^
                                     |
                         GET /customer-dashboard/42

You trade immediate consistency for predictable reads. That trade can be excellent when the product allows it, but it should be explicit.

CQRS does not mean two databases and a message bus

The useful idea behind CQRS is simply that the shape optimal for writes does not always match the shape optimal for reads.

You can start small:

  • transactional domain tables for writes;
  • purpose-built SQL projections for important reads;
  • separate DTOs and query handlers.

Only introduce separate stores, asynchronous projections and larger architecture when the load or domain justifies them.

Architecture diagrams do not create scalability by themselves.

Cache after you understand the data path

Caching can be enormously effective for repeated reads. It can also preserve a bad query behind a temporary layer of complexity.

Before adding a cache, know:

  1. what operation is expensive;
  2. how frequently the same result is reused;
  3. how stale it is allowed to be;
  4. how invalidation works;
  5. what happens on a miss;
  6. what happens when the cache is unavailable.

A cache miss path must still be safe. Otherwise a cache outage becomes a database outage.

Beware the cache stampede

Suppose a popular value expires and 5,000 requests arrive simultaneously. If every miss regenerates it, the cache has converted one expiry into 5,000 origin requests.

Useful techniques include:

  • request coalescing/single-flight;
  • stale-while-revalidate patterns;
  • jittered expiration times;
  • proactive refresh for extremely hot keys.

We will look at HTTP caching and distributed caching more deeply later in the series.

Do not cache authorization mistakes

Caching personalised or tenant-scoped data under an incomplete key can leak data between users.

This is unsafe conceptually:

cache key: customer:42

if the representation changes based on tenant, caller permissions, locale or other request context.

Cache keys and HTTP Vary behaviour must reflect every dimension that changes the representation, or the response should not be shared that way.

Correctness beats hit rate.

Read replicas are not free scale

Replicas can move read traffic away from the primary database, but introduce operational realities:

  • replication lag;
  • read-after-write inconsistency;
  • failover behaviour;
  • connection routing;
  • more infrastructure to observe.

If a user updates their profile and immediately reads stale data from a replica, the API may appear broken even though every component is “healthy”.

Route consistency-sensitive reads appropriately or design the user experience around the consistency model.

Batch carefully

Batch endpoints can reduce network overhead:

POST /customers:batchGet

But 10,000 IDs is not a reasonable substitute for 10,000 individual requests.

Set a maximum batch size and consider partial failure semantics explicitly.

For example:

{
  "results": [
    { "id": "1", "status": 200, "value": { ... } },
    { "id": "2", "status": 404 }
  ]
}

If operations need atomic all-or-nothing semantics, say so. If they do not, do not hold giant transactions open just because the requests arrived together.

Keep transactions short

Database transactions are for maintaining consistency, not for wrapping an entire HTTP request.

Avoid:

BEGIN TRANSACTION
  update database
  call payment provider
  send email
  wait for another service
COMMIT

Long transactions hold locks/resources and create ugly failure modes.

For workflows crossing service boundaries, use patterns such as durable state transitions, outbox/event publishing, idempotent consumers and compensating actions where appropriate.

Do not pretend a local database transaction can make a remote HTTP service atomic.

Measure tail latency, not just averages

An average API latency of 80 ms can hide a terrible user experience:

p50  = 45 ms
p95  = 420 ms
p99  = 2.8 s

The slow tail often exposes lock contention, cold caches, pool waits, noisy queries or unreliable dependencies.

Track latency by route and outcome, and segment it enough to find the actual problem. One global api_latency chart is rarely sufficient.

A data-path review checklist

For each high-traffic endpoint, answer:

  • Is request work bounded?
  • Is pagination enforced server-side?
  • Is ordering deterministic?
  • Are important queries supported by appropriate indexes?
  • Have actual execution plans been inspected?
  • Are responses projected rather than serialising full entities?
  • How many DB round trips does one request generate?
  • Are there N+1 patterns?
  • Is an exact total count genuinely necessary?
  • Can cancellation reach the database/dependencies?
  • Are connection-pool waits observable?
  • Does the endpoint fan out to other services?
  • Would a read model simplify the hot path?
  • If caching is used, is invalidation defined?
  • Is the miss path safe under load?
  • Can cache keys cross tenants/users accidentally?
  • What do p95 and p99 look like with production-shaped data?

That list catches more real scaling problems than prematurely splitting a service into microservices.

What comes next

Once individual requests perform bounded, efficient work, the next problem is traffic itself. Part 3 covers HTTP caching, conditional requests, rate limiting, overload protection, timeouts, retries, idempotency and the patterns that keep an API alive when dependencies start failing.

Ready to audit your site?

Put this guide into practice immediately using our free tools.

Browse 180+ Free Tools