DEV Community

Cover image for How Does a Background Job Know the Database Is Busy?
Vasyl
Vasyl

Posted on Originally published at vasyl.blog

How Does a Background Job Know the Database Is Busy?

Imagine Black Friday, 9 PM. Checkout gets slow. The p99 latency jumps from 80 ms to 4 seconds. Nobody deployed anything. No server is down.

The cause is a CSV export that someone in the back office started an hour ago. It reads the orders table as fast as it can. The database is not broken. It is just serving the wrong customer first.

How was the export supposed to know that it should step aside? That is what this post is about.

TL;DR: A background job and a checkout request use the same database. The request cannot wait. The job can. So the job checks the health of the database between batches and pauses when the database is busy. The usual signal is replication lag. If you cannot read that signal, measure the time of your own queries and adapt.

Why this post

I wrote a small GraphQL server to learn how bulk exports work. One line in the server stopped me:

while (databaseLoad.Percent > 70) await Task.Delay(100);
Enter fullscreen mode Exit fullscreen mode

In my server, I set databaseLoad by hand. A real system has no such number. So how does a real job know that the database is busy? I had never seen that code. This post is what I found.

Before: a naive export job

while (true)
{
    var rows = await database.ReadBatch(afterId: lastId, batchSize: 1000);
    if (rows.Count == 0) break;

    await file.WriteRows(rows);
    lastId = rows[^1].Id;
}
Enter fullscreen mode Exit fullscreen mode

This code works. That's the problem. It reads as fast as the database can answer. For one million rows, it keeps the database busy for minutes, with no pause.

At the same time, a customer clicks "Pay". Their request waits in line behind an export that nobody is looking at.

Request (checkout) Job (export, backfill)
Who is waiting a person nobody
How long the work takes milliseconds minutes or hours
Can the work wait no yes

The job loses nothing if it finishes ten minutes later. So the job must wait, not the customer.

Highways solved this first

A red ramp meter signal next to a sign that says One Car Per Green
One car per green. Photo: U.S. Federal Highway Administration.

You have probably seen this on a highway on-ramp: a small traffic light that lets cars in one at a time. It is called a ramp meter.

A ramp meter does not guess. Sensors in the road measure the traffic on the highway, and a computer changes the timing of the light. In Minnesota, for example, the timing adjusts every 30 seconds. When the highway is busy, the light stays red longer. When the highway is free, cars go almost without stopping.

This is exactly our problem:

  • The highway is live traffic: checkout requests.
  • The cars on the ramp are the batches of your job.
  • The sensors are the signal: replication lag, query time.
  • The red light is the pause.

The rest of this post builds a ramp meter for a database.

Three words that people mix up

  • Backpressure is the signal. A busy system says "slower" to the sender of the work.
  • Throttling is the action. The sender slows down on purpose.
  • Rate limiting is a fixed limit for a client: at most N in a period of time.

Rate limiting protects the server from clients. Backpressure protects the server from its own jobs.

Step 1: pick a signal

A database has no single "load" number. You measure some signals and compare each signal with a threshold.

Signal Where it comes from
Replication lag MySQL: SHOW REPLICA STATUS. PostgreSQL: pg_stat_replication
Active queries MySQL: Threads_running. PostgreSQL: pg_stat_activity
Query time (p95, p99) application metrics
Wait time for a connection connection pool metrics

For background jobs, the main signal is replication lag. Replication lag is the number of seconds that a replica is behind the primary.

Replication lag is a good signal for two reasons. First, the number shows the result, not the cause. If the replicas are behind, someone writes too much. Second, the threshold is easy to choose: for example, 1 second.

Step 2: check between batches

The job asks one cheap question before each batch. If the lag is above the threshold, the job waits.

async Task WaitWhileDatabaseIsBusy(ExportJob job)
{
    while (await replica.GetLagSeconds() > 1.0)
    {
        job.WaitingOnDatabase = true;
        await Task.Delay(TimeSpan.FromSeconds(1));
    }
    job.WaitingOnDatabase = false;
}
Enter fullscreen mode Exit fullscreen mode

Three details are easy to forget:

  • Do not check on every row. The check has a cost too. Check one time for each batch.
  • Do not block the thread. await Task.Delay frees the thread, so the server continues to answer requests.
  • Show that the job waits. The status stays RUNNING. A flag such as WaitingOnDatabase tells the client that the job is paused, not broken.

When you have hundreds of jobs, move the check into one service. Each job asks the service: "can I go?" Then the thresholds are in one place, and you can stop all background work with one command.

Step 3: no metrics? Measure your own queries

Sometimes a job cannot read database metrics. The job always has a stopwatch.

When the database is free, a batch of 1000 rows takes 50 ms. If the same batch now takes 400 ms, the database is busy. You do not need to know why.

var stopwatch = Stopwatch.StartNew();
var rows = await database.ReadBatch(afterId: lastId, batchSize);
var batchMilliseconds = stopwatch.ElapsedMilliseconds;
Enter fullscreen mode Exit fullscreen mode

Way A: rest in proportion to the work.

await Task.Delay(TimeSpan.FromMilliseconds(batchMilliseconds * 2));
Enter fullscreen mode Exit fullscreen mode

The job worked for 50 ms, so the job rests for 100 ms. When the database answers slowly, the pause becomes longer. The job uses the database for one third of the time at most.

Way B: change the batch size (AIMD).

AIMD means "additive increase, multiplicative decrease". TCP uses the same rule to control its speed on a network.

const int TARGET_MILLISECONDS = 100;

averageMilliseconds = averageMilliseconds * 0.8 + batchMilliseconds * 0.2;

if (averageMilliseconds > TARGET_MILLISECONDS)
    batchSize = Math.Max(100, batchSize / 2);        // slow: cut in half
else
    batchSize = Math.Min(10_000, batchSize + 100);   // fast: add a little
Enter fullscreen mode Exit fullscreen mode

The two branches are different on purpose. The job increases its speed slowly and decreases its speed quickly. Too much load on the database is worse than a job that is a little slow.

The moving average is there because one batch can be slow by accident. A new measurement counts for 20%, so one slow batch changes almost nothing.

Here is what this code does in practice. I ran it as a small simulation. In the middle, a "checkout rush" makes every batch 4 times slower:

Chart of the job's batch size: a sawtooth between 1200 and 2400 rows, falling below 800 during a checkout rush, then climbing back
The Way B code, simulated. Slow climb, fast drop. When the rush ends, the job takes its speed back by itself.

The sawtooth is the signature of AIMD. TCP draws the same shape on a network.

The blind spot

A job reads from a replica, and the replica answers quickly. At the same time, the primary has too many writes. The job cannot see this problem from its own queries.

So large systems use both. Replication lag is the main signal. The time of the job's own queries is the second check.

How real tools do it

Most developers never write this code. One team writes it one time, in a shared library or a service.

  • freno (GitHub) is the throttler service from Step 2. The README calls it a "cooperative, highly available throttler service". freno throttles clients when replication lag is above a threshold. A client sends a HEAD request to a /check/... endpoint. 200 means "write". 429 means "do not write now".
  • gh-ost (GitHub) changes the schema of large MySQL tables while the site works. gh-ost copies rows in chunks. --max-lag-millis pauses the copy when a replica is too far behind. --max-load pauses the copy on status values such as Threads_running=100. --nice-ratio is Way A: with --nice-ratio=1, gh-ost sleeps 1 ms for each 1 ms of copy time.
  • job-iteration (Shopify) makes Ruby jobs interruptible and resumable. Its throttle enumerator takes a throttle_on signal that you supply. If the signal is true, the library puts the job back in the queue for later. The guide says that Shopify's own signal checks replication lag and database threads.

Quick checklist

  • The job reads in batches and remembers the last id.
  • The job checks the health of the database one time for each batch.
  • The main signal is replication lag, with a clear threshold.
  • The wait does not block a thread.
  • The client can see the difference between "paused" and "broken".
  • The job reads from a replica when stale data is acceptable.
  • Checkout requests never go through this check.

The 30-second summary

Background jobs yield to live traffic, because a job can wait and a customer cannot. There is no single "load" number, so the job checks replication lag between batches and pauses above a threshold. If the job cannot read database metrics, it measures its own batch time and adapts: add a little when the database is fast, cut in half when the database is slow. Show a "waiting" flag, so nobody thinks the job is broken.

That's it. Have you seen a background job take down a production database? Tell me in comments. 🙂

Originally published on vasyl.blog.

Top comments (1)

Collapse
 
robertpaschal profile image
Odinaka Robert Nnamani •

the export reads as fast as the database answers and checkout waits behind it. checking between batches is the whole fix.