What Concurrency Changes When a Background Task Reads Your Database

A report approaches an amber threshold on one conveyor while the receiving tray on a parallel conveyor is still empty.

You create a report. The API returns success, and the report appears in the list. When you open it, the PDF preview is missing. The background worker had the right report ID. Its database query ran too early.

The report and its preview have different lifetimes. The request creates the report in a database transaction. A background job fetches the report by ID and prepares a preview. This article uses Spring’s imperative JDBC stack and a local PostgreSQL database to show where those two lifetimes cross.

What will the worker see?

In the lab, the service and the worker are separate Spring beans. The insert helper executes the JDBC statement immediately. The bounded wait pins the worker’s read before the method returns so you can reproduce the timing.

@Transactional(timeout = 15, rollbackFor = Exception.class)
public int createTooEarly(UUID id, String title) throws Exception {
    int requestPid = insert(id, title);
    var attempt = worker.prepare(id);
    // Lab gate: keep the transaction open until the worker has read.
    // A timeout fails the scenario and rolls the insert back.
    attempt.get(10, TimeUnit.SECONDS);
    return requestPid;
}

Pause at the worker’s SELECT. The request’s INSERT has succeeded, and the request transaction is still open. Can a plain SELECT on a second PostgreSQL connection at READ COMMITTED see the new report? What changes if the same query starts after commit?

The early query finds zero matching report rows. The transaction that inserted the row can read its own change. On the other connection, PostgreSQL’s plain SELECT uses a snapshot of changes committed when that statement starts. Once the request commits, a fresh SELECT can see the row. The older query keeps the snapshot it already took. PostgreSQL 17 isolation documentation

Read before commit

RequestBackground job
Run INSERT
Call worker proxy
Submit task
Start task
Transaction openRun SELECT
0 reports
COMMIT

Read after commit

RequestBackground job
Run INSERT
Publish event
COMMIT
Listener submits task Start task
Run SELECT
1 report
Time moves down each panel. The request column follows the transaction. The background job reads through a separate PostgreSQL connection.

Follow the call, the task and the commit

The caller enters the report service through its Spring proxy, which opens the transaction in this example. The service runs the INSERT on the request thread’s bound JDBC connection. Then the call to worker.prepare(id) enters another proxy, which submits a task to the configured executor. The actual worker method runs when that task starts. When the report method returns normally, Spring can commit the transaction it opened. If this method joins an existing transaction, the outer boundary owns the commit. Spring’s transaction annotation · Spring Transactions for Beginners

Those are separate steps. An idle executor can start the task before the request returns. A busy executor might start it after commit, which can make the original code appear to work. A call to an @Async method on the same instance bypasses the default proxy and runs inline. In the example, the injected worker bean gives Spring a proxy boundary to intercept. Spring’s imperative transaction is bound to the calling thread, so the worker’s JDBC query acquires a different connection. Spring’s task execution and scheduling reference

Concurrency here means that the request and worker lifetimes overlap. The request can be waiting while the worker runs its query. Only the order INSERT → SELECT → COMMIT is needed for the miss, so concurrent execution on one CPU core is enough. Parallel execution on multiple cores is a separate question. A different executor or virtual threads can change how quickly the task starts. A worker transaction gives the worker its own database boundary. None of those choices establishes that its query starts after the request commits. Concurrency vs Parallelism in Java and Spring · Java virtual threads

Submit the task after commit

Publish a small application event while the request transaction is still active. The event carries an immutable UUID. The worker fetches the data it needs using that ID.

record ReportCreated(UUID reportId) {}

@Transactional(timeout = 15)
public int create(UUID id, String title, boolean rollBack) {
    int requestPid = insert(id, title);
    events.publishEvent(new ReportCreated(id));
    if (rollBack) {
        throw new DemoRollback();
    }
    return requestPid;
}

In another Spring bean, a transaction-bound listener receives the event after a successful commit. Its only job is to call the async worker through the worker’s proxy.

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
void submitPreview(ReportCreated event) {
    worker.prepare(event.reportId());
}

The worker declares which executor runs the task. Its read helper queries the report by ID through JDBC and prepares the preview text if it finds the report. The lab records the observed isolation level and connection identity in the result.

@Async("previewExecutor")
public CompletableFuture<PreviewRead> prepare(UUID id) {
    PreviewRead result = read(id);
    // A local observation for the lab. The preview is only a string.
    events.publishEvent(result);
    return CompletableFuture.completedFuture(result);
}

AFTER_COMMIT chooses the transaction phase. In this example, the listener runs synchronously on the request thread during transaction completion, and only the handoff to the executor makes the preview computation asynchronous. If the request rolls back, this listener skips submission. The default fallbackExecution = false also skips callbacks for events published without a transaction. Spring transaction-bound events

If a synchronous listener must write to the database, give that write a new transaction, for example by calling a separate Spring bean with @Transactional(propagation = Propagation.REQUIRES_NEW). Spring’s Javadoc warns that the original resources may still be bound during the callback, even though the transaction has already committed. A write that participates in those resources has no later commit. A separate transaction gives the write its own commit and failure boundary. Listener Javadoc · Transaction synchronization Javadoc

Reproduce the three outcomes

Download the Spring async transaction lab (ZIP) and extract it. It uses Java 21 or later, Maven and Docker Compose. From the extracted lab directory, start the database, run the tests and stop the lab container when you are done.

docker compose up -d --wait --wait-timeout 30
mvn test
docker compose down

The tests call the proxied service outside a test transaction, so the service controls the real commit or rollback. The first case uses a bounded future wait to hold the request transaction open until the worker has read. In normal code that wait would be absent. Its purpose here is to force one valid schedule every time. The corrected test waits for the worker result after the call to the service, and the rollback test checks the executor’s submission count after the transaction completes.

The test asserts that PostgreSQL reports different backend process IDs for request and worker, and that the worker reads at READ COMMITTED. The lab uses a diagnostic left join to capture the connection ID and isolation even when the report is absent. The row counts below refer to matching reports. A string stands in for PDF generation.

The lab uses PostgreSQL 17.6, Spring Boot 4.2.0 and Spring Framework 7.1.0. It targets Java 21 and was also run on Java 27, the current feature release as of December 1, 2026. Java 25 is Oracle’s latest LTS line. The code uses stable APIs. Spring Boot system requirements · Oracle Java support roadmap · Current PostgreSQL isolation reference

Decide what a successful commit should guarantee

The after-commit listener solves the visibility problem. The report can still commit just before the process exits, or before a queued task starts. The report then survives and the preview job can be lost. That can be acceptable for a regenerable preview if opening the report can request it again and the user can tolerate the wait.

If every report must eventually get a preview, record the work durably in the same transaction as the report. One option is an outbox row containing the report ID and job identity. A dispatcher reads committed entries and retries unfinished work. A crash after preparing the preview but before marking the job complete can cause another attempt. Make the effect idempotent, for example by storing or replacing a preview under the same report ID and report version. The lab demonstrates commit ordering and rollback. Crash recovery and outbox retries are design scenarios discussed here. Spring Modulith’s event publication registry · Idempotency in Java and Spring

Structured concurrency can help when a request owns a group of subtasks and needs their outcomes before it can finish. A preview job with a lifetime beyond the request needs its own ordering and delivery rules. Java 27 Structured Concurrency

Choose when to run the work

ChoiceUse it whenWhat it guarantees
Immediate executionThe work is part of the request, or an independent task can use already committed data.Inline JDBC on the request connection can see its own writes. A separately submitted task can start while those writes are still uncommitted.
Execution after commitA task needs the committed row and can be requested again if lost.The in-process handoff follows successful commit. A rollback skips the handoff.
Durably registered background workEvery committed report must eventually receive a preview, including after a restart.The report and job record commit together. A dispatcher can resume and retry the job, and an idempotent handler makes repeated attempts safe.