Spring Builders

john clsads
john clsads

Posted on

How to Build an Idempotent Stop Endpoint for Live Sessions in Spring Boot

How to Build an Idempotent Stop Endpoint for Live Sessions in Spring Boot

A user clicks Stop. The browser closes its preview, the server records the request, and the provider takes a few seconds to confirm shutdown. If the browser retries after losing the first response, the server should return the existing stop state with the original usage cutoff and leave a single shutdown job for the worker.

In the Live Face Swap webcam studio we build, creators can end the live transformation and continue reviewing takes they already recorded. The server keeps the customer billing cutoff separate from provider shutdown confirmation and final settlement. A stop response can report that shutdown is still pending while the stored command gives the server a way to finish the work after the request ends.

Here is a Spring Boot and PostgreSQL example inspired by that workflow. It models a session that has already reached RUNNING. Each application session has an immutable ID and refers to one upstream session for the duration of this example.

Give the stop response a precise meaning

Use POST /sessions/{id}/stop with the owner identity derived from the authenticated principal. Return 202 Accepted with STOPPING after committing the stop request. Once the worker confirms closure, the same endpoint can return 200 OK with STOPPED. Include the current state and the stored cutoff in either response. Use an owner-scoped status endpoint so a client can check progress without sending another stop.

Here, STOPPED means the upstream session is closed. If your billing process needs a final usage report, keep its settlement status separate. The client can stop showing an active preview while both pieces of server work continue.

Write the cutoff and shutdown job in one transaction

The example uses JdbcClient from Spring Framework 6.1 or later. Assume live_session has a UUID primary key, a text owner ID, a state, and a nullable usage_cutoff_at column of type timestamptz. The cutoff is populated when the row enters STOPPING and stays populated after closure. Give session_stop_job.session_id a primary key and a foreign key to the session. The insert creates a pending job.

import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;

@Service
public class SessionStopService {
    public record StopAck(String state, Instant usageCutoffAt) {}

    private final JdbcClient jdbc;

    public SessionStopService(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    @Transactional
    public StopAck requestStop(UUID sessionId, String ownerId) {
        var cutoff = jdbc.sql("""
                update live_session
                   set state = 'STOPPING',
                       usage_cutoff_at = clock_timestamp()
                 where id = :id and owner_id = :owner and state = 'RUNNING'
                returning usage_cutoff_at
                """)
            .param("id", sessionId)
            .param("owner", ownerId)
            .query((rs, row) -> rs.getObject(1, OffsetDateTime.class).toInstant())
            .optional();

        if (cutoff.isPresent()) {
            jdbc.sql("insert into session_stop_job (session_id) values (:id)")
                .param("id", sessionId)
                .update();
            return new StopAck("STOPPING", cutoff.get());
        }

        return jdbc.sql("""
                select state, usage_cutoff_at
                  from live_session
                 where id = :id and owner_id = :owner
                """)
            .param("id", sessionId)
            .param("owner", ownerId)
            .query((rs, row) -> new StopAck(
                rs.getString("state"),
                rs.getObject("usage_cutoff_at", OffsetDateTime.class).toInstant()))
            .optional()
            .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
    }
}
Enter fullscreen mode Exit fullscreen mode

Call this method through the Spring-managed service so the update and job insert share one transaction. A job insert failure rolls back the state change and cutoff. Under PostgreSQL's default Read Committed isolation, a competing stop request waits for the row update and then rechecks the RUNNING predicate. Once the first request commits, the second skips the update and reads the stored state. The controller can map that state to its HTTP response after the service transaction commits.

For example, suppose the server stores a cutoff of 12:00:03.200, commits the transaction, and loses the response. A retry at 12:00:06.900 returns the same cutoff. If the worker confirms provider closure at 12:00:08.100, it can store the confirmation time separately for reconciliation.

Finish shutdown after the request ends

Have a worker claim pending jobs with a lease and contact the provider outside the database transaction. After it has evidence of closure, have it verify that it still owns the lease and mark the session stopped and the job completed in one transaction. If the process exits after the provider closes the session but before the database commit, a later worker will see the job again. Reuse a stable provider idempotency key where supported, or use the provider's status API and documented response semantics to establish whether the same session is already closed.

A lost stop signal is a different case because the server has no queued job to retry. If your session expires on heartbeat silence, have a periodic scan identify candidates and verify expiry again at the point of the stop transition. A heartbeat can arrive between scanning and updating. Rechecking under the session lock or in the guarded update protects a session that has just renewed its lease.

Which cases should you test first?

  • Two simultaneous stops. Both responses refer to the same cutoff. The job table has one row for that session.
  • A lost response after commit. The next request reads the same cutoff and reports the current state, which may already be STOPPED.
  • A provider timeout after receiving the close request. The job stays recoverable and the worker checks the provider outcome before marking it complete.
  • A late heartbeat during an expiry scan. The expiry check sees the renewed lease and skips the stop transition.

Top comments (0)