A Supervisor for A2A Agents in Spring Boot: Jobs in PostgreSQL, SKIP LOCKED Leases, Progress Over SSE, and Retries That Never Repeat Work
One jar runs four ways: a transcriber agent, a subtitle agent and two supervisor copies. A retried POST with the same Idempotency-Key gets 200 and the same job. Copy-a accepts, copy-b claims with SKIP LOCKED, and the progress stream shows four events. Kill copy-a after TRANSCRIBED and, once its 20 s lease runs out, the restarted copy runs only the subtitles.
What you will learn
- Run agents as A2A services with a card and an executor, and call them from a supervisor that knows only a URL
- Make job creation idempotent with a unique Idempotency-Key and ON CONFLICT DO NOTHING
- Share work between supervisor copies with FOR UPDATE SKIP LOCKED and a renewed lease
- Save each step before the next, stream progress from an events table, and recover from a crash mid-job
Before you start
- Spring Boot and JdbcClient
- The transcription and subtitle agents
- PostgreSQL transactions
CaptionDesk now has two agents, one for transcription and one for translation and review. In this step they become services of their own, and a supervisor turns every upload into a job kept in PostgreSQL. The goals: a job survives a crash, two supervisors share the work, and a retry never transcribes the same clip twice. The protocol itself is introduced in A2A, agent to agent.
One jar, four roles
java -jar target/caption-desk.jar --spring.profiles.active=transcriber
java -jar target/caption-desk.jar --spring.profiles.active=subtitler
java -jar target/caption-desk.jar --spring.profiles.active=supervisor
java -jar target/caption-desk.jar --spring.profiles.active=supervisor --server.port=18843 --supervisor.name=copy-b
A profile picks the role. The supervisor's profile file:
# The supervisor: owns the jobs table, calls the agents, serves progress.
# It is not an agent itself.
spring:
flyway:
enabled: true
ai:
a2a:
server:
enabled: false
supervisor:
name: copy-a
lease: 20s
The supervisor owns the database, so Flyway creates the job tables when it starts. It is not an agent, so the A2A server is off. The name says which copy holds a job, and the lease says how long it may hold one without a heartbeat.
Agents with a card
$ curl -s localhost:18841/.well-known/agent-card.json | grep -o '"name":"[^"]*"' | head -2
"name":"CaptionDesk Transcription Agent"
"name":"transcribe"
$ curl -s localhost:18842/.well-known/agent-card.json | grep -o '"name":"[^"]*"' | head -1
"name":"CaptionDesk Subtitle Agent"
Each agent publishes its card at the well-known address, with its name and skill. The transcriber's executor checks storage first:
/** Message: the upload id. A transcript already in storage is not made again. */
@Bean
AgentExecutor agentExecutor(ChatClient.Builder builder,
TranscriptionAgent agent, MediaStore store) {
return new DefaultAgentExecutor(builder.build(), (client, context) -> {
var message = context.getMessage();
String id = DefaultAgentExecutor.extractTextFromMessage(message).strip();
String key = "jobs/" + store.jobId(id) + "/transcript.json";
if (store.exists(key)) {
var t = store.getJson(key, TranscriptionAgent.Transcript.class);
int n = t.segments().size();
return "skipped: " + n + " segments already in storage";
}
...
var t = agent.transcribe(id, null);
...
});
}
Calling an agent over A2A
/** One A2A call: read the card, send one message, poll the task until it is final. */
public String call(String agentUrl, String text) throws Exception {
var card = A2ACardResolver.builder().baseUrl(agentUrl).build().getAgentCard();
var first = new CompletableFuture<Task>();
Client client = Client.builder(card)
.clientConfig(ClientConfig.builder().setStreaming(false).build())
.withTransport(JSONRPCTransport.class,
new JSONRPCTransportConfigBuilder())
.addConsumer((event, agent) -> {
if (event instanceof TaskEvent te) {
first.complete(te.getTask());
}
})
.build();
try {
client.sendMessage(A2A.toUserMessage(text));
Task task = first.get(60, TimeUnit.SECONDS);
long deadline = System.currentTimeMillis() + 600_000;
while (!task.status().state().isFinal()
&& System.currentTimeMillis() < deadline) {
Thread.sleep(500); // the agent keeps the task
task = client.getTask(new TaskQueryParams(task.id()));
}
...
} finally {
client.close();
}
}
The card says where and how the agent listens. Translation can take minutes, so instead of waiting on one call, the agent keeps the task and the supervisor polls it by id until it is final. The supervisor never imports an agent class. It knows a URL and the protocol.
A retried POST gets the same job
/** Same Idempotency-Key, same job: a retried POST never creates a second one. */
@Transactional
public Created create(UUID uploadId, String lang, String key, String owner) {
UUID id = UUID.randomUUID();
int added = db.sql("""
INSERT INTO job (id, upload_id, lang, idempotency_key, state)
VALUES (?, ?, ?, ?, 'QUEUED')
ON CONFLICT (idempotency_key) DO NOTHING""")
.params(id, uploadId, lang, key).update();
Job job = db.sql("SELECT id, upload_id, lang, state, owner FROM job"
+ " WHERE idempotency_key = ?")
.param(key).query(Job.class).single();
if (added == 1) {
event(job.id(), owner, "QUEUED", "accepted, key " + key);
}
return new Created(job, added == 1);
}
$ curl -s -w ' %{http_code}\n' -X POST -H 'Idempotency-Key: bakery-es-1' "localhost:18840/jobs?upload=$UP&lang=es"
{"job":"7a5768ff-6d56-4bdc-adc7-30a8892051d5","state":"QUEUED","new":true} 201
$ curl -s -w ' %{http_code}\n' -X POST -H 'Idempotency-Key: bakery-es-1' "localhost:18840/jobs?upload=$UP&lang=es"
{"job":"7a5768ff-6d56-4bdc-adc7-30a8892051d5","state":"QUEUED","new":false} 200
The key is unique in the table, so the second insert does nothing, and the read by key returns the one job. The table holds one row.
Two supervisors, one claim
/** The oldest unfinished job nobody holds. Two copies never take the same row. */
@Transactional
public Optional<Job> claim(String owner, Duration lease) {
return db.sql("""
UPDATE job SET owner = :owner,
lease_until = now() + make_interval(secs => :secs)
WHERE id = (SELECT id FROM job
WHERE state <> 'DONE'
AND (lease_until IS NULL OR lease_until < now())
ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED)
RETURNING id, upload_id, lang, state, owner""")
.param("owner", owner).param("secs", lease.toSeconds())
.query(Job.class).optional();
}
FOR UPDATE SKIP LOCKED means that if another copy is claiming a row right now, this copy skips it instead of waiting. There is no leader and no lock service: PostgreSQL decides who works on what.
@Scheduled(fixedDelay = 1000)
public void work() {
jobs.claim(name, lease).ifPresent(job -> {
jobs.event(job.id(), name, job.state(), "claimed by " + name);
// renew the lease while we work; if this copy dies, the lease runs out
var beat = heartbeat.scheduleAtFixedRate(
() -> jobs.renew(job.id(), name, lease), 5, 5, TimeUnit.SECONDS);
try {
String state = job.state();
if (state.equals("QUEUED")) {
String done = agents.call(transcriber, job.uploadId().toString());
jobs.advance(job.id(), name, "TRANSCRIBED", done);
state = "TRANSCRIBED";
}
if (state.equals("TRANSCRIBED")) {
String ask = job.uploadId() + " " + job.lang();
String done = agents.call(subtitler, ask);
jobs.advance(job.id(), name, "DONE", done);
}
} catch (Exception e) {
...
} finally {
beat.cancel(false);
jobs.release(job.id(), name);
}
});
}
The state is the last step that finished, and each step is saved before the next starts. That is where a restart begins: if the state is TRANSCRIBED, transcription is not run again. The lease is renewed every five seconds while a step runs, and a copy that dies stops renewing.
Progress from the table
/** Progress as server-sent events, read from the table: any copy can serve it. */
@GetMapping(value = "/jobs/{id}/events", produces = "text/event-stream")
public SseEmitter events(@PathVariable UUID id) {
var emitter = new SseEmitter(900_000L);
streams.submit(() -> {
long seen = 0;
try {
while (true) {
for (var e : jobs.events(id, seen)) {
emitter.send(SseEmitter.event().name("progress")
.data(e.owner() + " " + e.state() + ": " + e.note()));
seen = e.seq();
if (e.state().equals("DONE")) {
emitter.complete();
return;
}
}
Thread.sleep(300);
}
} catch (IOException | InterruptedException ex) {
emitter.completeWithError(ex);
}
});
return emitter;
}
The stream is deliberately opened on copy-b:
$ curl -sN --max-time 900 localhost:18843/jobs/$JOB/events
event:progress
data:copy-a QUEUED: accepted, key bakery-es-1
event:progress
data:copy-b QUEUED: claimed by copy-b
event:progress
data:copy-b TRANSCRIBED: transcribed 6 segments, 24.4 s of audio in 8.8 s
event:progress
data:copy-b DONE: review: all 6 lines pass
Copy-a accepted the job, copy-b claimed and ran it, and the stream closed at DONE. The client does not care which copy did what.
A crash in the middle of a job
Copy-b is stopped and a German job is sent for the same clip. Copy-a is killed right after TRANSCRIBED and started again:
$ curl -sN --max-time 900 localhost:18840/jobs/$JOB2/events
event:progress
data:copy-a QUEUED: accepted, key bakery-de-1
event:progress
data:copy-a QUEUED: claimed by copy-a
event:progress
data:copy-a TRANSCRIBED: skipped: 6 segments already in storage
event:progress
data:copy-a TRANSCRIBED: claimed by copy-a
event:progress
data:copy-a DONE: review: 1 of 6 lines flagged
The transcriber skipped the work, because the transcript was already in storage. After the kill, the saved state stayed TRANSCRIBED, owned by a copy that no longer renewed its lease. Once the 20-second lease ran out, the restarted copy claimed the job again and ran only the subtitles. One of six lines was flagged for a person. The stream stayed open for about five minutes, mostly translation on the shared model. A step is saved before the next one starts, so a crash costs at most one step. The same idea for long agent runs is in durable agent runs.
Four failures, four guards
| Failure | Guard | Seen in the run |
|---|---|---|
| The client retries a POST | Unique Idempotency-Key | 201, then 200, one row |
| Two supervisors poll at once | FOR UPDATE SKIP LOCKED | Copy-b took the job, copy-a did not |
| A supervisor dies mid-job | State per step, a lease that runs out | The restarted copy finished from TRANSCRIBED |
| A step is asked for twice | The agent checks storage first | "skipped: 6 segments already in storage" |
Each guard is a few lines, and each lives in the table or in storage, not in memory. Keep the state in the table, and every copy can do the work.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
What Spring AI 2 Is, and Why a Java Team Wants It
Spring AI 2 is one Spring-style API for AI models: your code talks to a ChatClient, and the provider is a dependency and a setting. Follow one 'I was charged twice' call through advisors and the model to a Java record, see why 20,000 tickets a day is more than one HTTP call, and what the library leaves to you.
Spring AI ChatClient: One API for Any Model, and the Model Is a Property
A small Spring Boot chat service asks llama3.2:3b in Docker through one ChatClient chain, reads 43 tokens in and 60 out from the response, gets the same answer twice at temperature 0 with seed 42, then moves to llama3.2:1b with one environment variable and no code change.
Spring AI Prompt Templates: Placeholders, Few-Shot Messages and Versioned Prompt Files
PromptDesk keeps its prompts in .st files with {customer} and {ticket} placeholders, picks ticket-summary-v1 or v2 with one property, turns a chatty 'I would classify this as BUG' into plain BUG with two example messages, and refuses to send a prompt with a hole in it.
Spring AI Structured Output: From Model JSON to a Java Record, and a Real Ticket Triage Feature
A Triage record with two enums becomes the contract with the model. On llama3.2:3b only native structured output returned a valid record; format text alone left the JSON unclosed and the validation advisor tried three times for the same broken answer. Then Relay's triage: the model picks a category and priority, a config table picks the agent, and a dead model costs the customer one second, not seventy.
