In my video-call app, a paid API call could be billed twice and the run would still end as a success. If a request reaches the provider and only the reply is lost, the retry bills a second time, and the second reply looks like a normal success.

After a call is recorded, the app can transcribe the file, summarize the transcript, upload it, save the results and notify the participants. Two of those steps are paid calls, today ElevenLabs for the transcript and Anthropic for the summary. The chain uses Temporal, a workflow engine: it performs the steps, stores the progress in a database and resumes the job after a crash or a deploy. To resume, it retries the interrupted step, which is how the second bill happens.

Temporal does not prevent this. It retries a step that timed out, as a queue redelivers a message that was not acked. What stops the second bill is a ledger on disk: one JSON file per recording and step, and one rule. If an earlier attempt may have reached the provider, do not send the request again.

The rest of the post explains how the parts work together, then puts the rule to the test: the worker is stopped with SIGKILL at nine crash points, and three services around it fail. SIGKILL ends a process at once, and the process cannot handle it (signal(7)).

Temporal basics

Temporal has three parts: the server, which schedules the work; a database such as Postgres, where the server stores a run’s progress; and the Go SDK, a library the worker uses to define workflows and activities and to poll the server.

Workflows, activities and the worker

In Temporal, code is written as workflows and activities. A workflow is the function that defines the steps and their order; in this app, that is PostProcessWorkflow. An activity is a function with side effects, such as a call to a provider or a write to MongoDB. The chain’s activities are Transcribe, Summarize, Upload, Persist and Notify. A workflow never calls a provider: it asks Temporal to start an activity and waits for the result.

The workflow only schedules activities and reads their results:

// from call-transcriber/internal/recordingflow/workflow.go; step choice, statuses and logging removed, branches condensed
func PostProcessWorkflow(ctx workflow.Context, in Input) (Result, error) {
	paid := workflow.WithActivityOptions(ctx, paidOptions)
	var a *Activities
	var res Result
	if err := workflow.ExecuteActivity(paid, a.Transcribe, in).Get(ctx, &res.Transcript); err != nil {
		res.degrade("transcribe", err) // no transcript: the summary is skipped
	} else if err := workflow.ExecuteActivity(paid, a.Summarize, in, res.Transcript).Get(ctx, &res.Summary); err != nil {
		res.Summary = Extractive(res.Transcript) // the basic summary
		res.degrade("summarize", err)
	}
	// then Upload, Persist and Notify the same way
	return res, nil
}

Workflows and activities stay off the Temporal server. They live in a worker, a separate service: for this chain, the recording-worker container. The worker polls the Temporal server for its next step, like a NATS pull consumer reading from a work queue.

History and replay

For each run, the server keeps a history: an append-only list of events. Take a worker that ends abruptly during the summary, for example when the host runs out of memory and the system stops it with SIGKILL. The run looks like this:

# Example history of one run; Temporal's own bookkeeping events removed
1 WorkflowExecutionStarted   session s1, steps: transcribe, summarize
2 ActivityTaskScheduled      Transcribe
3 ActivityTaskCompleted      Transcribe -> "hello, this is the call..."
4 ActivityTaskScheduled      Summarize
  <- worker killed: no ActivityTaskCompleted for Summarize

After a restart, the worker has lost the previous process’s memory: the workflow’s result so far (res in the listing above) is gone. Temporal hands it the history, and the worker calls PostProcessWorkflow again from the start. This is replay. Each ExecuteActivity(...).Get whose activity already has a result in the history returns that result at once: Transcribe returns the stored transcript, and the provider is not called. Replay ends at the first activity with no result, Summarize in the listing above. From there, Temporal schedules a new attempt of Summarize, and the worker executes it.

Replay works only if the workflow asks for the same activities in the same order on every run. Temporal therefore requires workflow code to be deterministic: no clock reads, no random numbers and no I/O. The Go SDK provides workflow.Now in place of time.Now, and I/O belongs in activities.

Timeouts, heartbeats and retries

Temporal notices a dead worker with timeouts. Each attempt of an activity has a start-to-close timeout, the longest a single attempt may take. Heartbeats are optional: an activity that calls activity.RecordHeartbeat every few seconds tells Temporal its worker is alive, and a heartbeat timeout sets how long Temporal waits without a heartbeat. If the heartbeats stop for longer than that, Temporal fails the attempt and schedules another, instead of waiting for the whole start-to-close timeout. The catch is that a heartbeat says the process is alive, not that the provider call is progressing.

Every activity that may take long starts a heartbeat when it begins and stops it when it returns:

// from call-transcriber/internal/recordingflow/workflow.go; logging and the other activities removed
const heartbeatTimeout = 20 * time.Second

func (a *Activities) Transcribe(ctx context.Context, in Input) (string, error) {
	defer heartbeat(ctx)() // beat until Transcribe returns
	text, err := a.Transcriber.Transcribe(ctx, in.SessionID)
	return text, paidError(err) // only a 429 or 5xx may be retried
}

// heartbeat beats until the returned stop is called.
func heartbeat(ctx context.Context) (stop func()) {
	done := make(chan struct{})
	go func() {
		t := time.NewTicker(heartbeatTimeout / 4) // every 5 s
		defer t.Stop()
		for {
			select {
			case <-t.C:
				activity.RecordHeartbeat(ctx)
			case <-done:
				return
			}
		}
	}()
	return func() { close(done) }
}

A retry policy sets what happens next: the delay before the next attempt, and how many attempts are allowed. An activity can also return a non-retryable error, which ends the retries at once whatever the policy says.

The history also explains how a paid call can be sent again. An activity with a completed event never starts again, but an activity without a completed event does, even if the first attempt did all its work and died before reporting it. For Summarize, that is a second paid call to the model. Temporal runs activities at least once, as a NATS consumer handles messages; the ledger turns that into at most one paid call per step.

What happens after a call is recorded

From the user’s side, the choice comes before the recording starts. Next to “Start Recording”, a menu offers “No transcript”, “Transcript” or “Transcript and summary”, with the price and the provider that will receive the audio. The default is no transcript. When the run ends, the recording appears in the group’s list, with the summary and transcript in a side panel. Any group member can later ask for a step that was not chosen: a recording with a transcript and no summary shows a “Summarize” button.

When a recording is saved, the backend (the app’s Node.js API) writes the file to a directory on the host that the worker also mounts, and publishes recording.stored on NATS. The event carries the session ID and the steps chosen by the user who started the recording.

The recording-worker container is the Temporal worker. It also hosts a NATS consumer: for each recording.stored event, the consumer asks Temporal to start one workflow, and the worker then picks up that workflow and its activities. The paid steps record their calls in the ledger, a directory of JSON files on a Docker volume. The workflow ID is the session ID, and Temporal rejects a second start with that ID, whether the first run is open or closed. A redelivered event is acked and starts no second run.

The diagram below maps the parts of the chain.

Where the chain lives: the backend writes the recording file to a host directory and publishes recording.stored on NATS. Inside the recording-worker container, one process, a NATS consumer pulls the event and starts a workflow on the Temporal server, whose Postgres keeps the run histories. The Temporal workflow and activities poll the server for tasks, read the file, record paid calls in the ledger files on a Docker volume that survives the container, call the paid providers to transcribe and summarize, upload to R2, persist to MongoDB and notify through NATS

The first run, started when the recording is saved, has up to five steps. The first two are paid, and the user chooses them:

  1. Transcribe the file with a speech-to-text provider (paid, optional).
  2. Summarize the transcript with a language model (paid, optional, needs a transcript).
  3. Upload the file to object storage (R2).
  4. Persist the transcript, summary and object key with the recording’s entry in MongoDB.
  5. Notify the app through a NATS event.

A later request for a step that was not chosen starts a separate, shorter run, described below.

The order follows what each step needs. Summarize reads the transcript. Transcribe reads only the local file, and Upload can delete it (UPLOAD_DELETE_LOCAL=true, off by default). So Upload comes after the paid steps. Persist and Notify come last because they save and announce the results.

When a paid step still fails after its retries, the run is degraded, not failed. Without a transcript, the summary is skipped. Without a summary from the model, the workflow builds a basic summary from the transcript itself, with no model call. The recording is still uploaded, saved and announced, and the reason goes on the result. A failed Upload also degrades the run, and the local file is kept. Only a failed Persist or Notify fails the run.

A later request starts with the backend. It refuses a step that is already done, a step whose last outcome was unknown (the ledger counts it as spent), and a transcript once Upload has deleted the local file. Otherwise it publishes recording.process, and the worker starts a separate run. That run’s ID is built from the session ID and the requested steps, and is allowed again once the earlier run with that ID has closed. It skips the upload and, for a summary, reads the stored transcript from MongoDB.

A paid step leaves a record in two places: Temporal’s Postgres keeps whether the activity completed, and the ledger keeps whether the provider was called. The two records can differ. After a crash, Temporal may still list a step as unfinished when the ledger already has a call for it. The next attempt reads the ledger first and makes no second call. The ledger lives on the container’s Docker volume: a recreated container keeps it only if the volume is kept.

How the ledger stops a second bill

Before the recording chain, I built a text-to-speech prototype that read a call’s transcript aloud as a spoken recap. It was a NATS consumer with two safety checks: it skipped a recording whose recap file already existed, and a per-recording mutex lock made a redelivery wait while the first delivery was still calling the provider, before the file existed. Its tests passed, including a test that delivered the same message five times and counted a single call. Simplified, the guard looked like this:

mu.Lock() // one delivery per recording at a time
defer mu.Unlock()
if fileExists(path) {
	return nil
}
audio, err := tts.Call(ctx, text) // paid; a timeout ends up here
if err != nil {
	return err // NATS delivers the message again
}
return writeFile(path, audio)

None of them made the provider time out: the client stopping its wait before the reply arrives, while the provider may still be working. A timeout is not an error from the provider: the provider may have done the work and billed it. The consumer treated it as a failure and asked JetStream to deliver the message again, and each redelivery sent the call once more, up to the consumer’s limit of five deliveries (MaxDeliver). If the provider had billed the first request and the audio was lost on the way back, the recap could be billed five times.

The fix was a marker file, <recording>.pending, created before the request and kept until the provider answered. If the marker already exists, an earlier attempt may have been billed, and the code does not send the request again. A test of the marker turned up a defect: when the daily spending cap refused a request, the code left the marker in place, as if the provider might have billed, and the recap stayed blocked even after the cap reset. When the cap refuses a request, it never reaches the provider, so the code now removes the marker.

The prototype gave me a rule: if a request may have reached the provider, do not send it again. A timeout or a lost connection counts as reached. Its cost is a lost recap for every timeout, until someone deletes the marker by hand. For an optional recap, I accept that loss: a missing recap costs the user a convenience, while sending the request again would risk a second bill on every timeout. A paid recap would need more: a retry that the user starts, or an idempotency key from the provider (a unique token that makes the provider return the first result instead of billing again).

The recording chain has two paid steps that can time out the same way. A worker can end abruptly in the middle of a transcription call: a crash, an out-of-memory kill or a host failure. The process stops there, so the reply is lost, and Temporal is left with the question the NATS consumer had: did the provider bill? Temporal cannot know, and its retry policy would call the provider again. So that rule became a ledger on disk, one JSON file per recording and step. Every paid step goes through it:

ledger functionwhen the step uses itwhat it does
Beginbefore the provider callreserves the cost; refuses if the entry is pending or spent, or if a cap would be crossed
Finishthe provider repliedstores the result; a later attempt gets it back and makes no call
Unknowntimeout or lost connectionmarks the entry spent; the cost stays counted
Cancelthe provider answered with an errorremoves the reservation; the step may try again

An entry is replaced by writing a temporary file, flushing it to disk and renaming it over the old file. A crash leaves the old entry or the new entry, never a half-written file.

The transcription step follows the prototype’s order: reserve first, then call the provider:

// from call-transcriber/internal/transcribe/transcribe.go; one comment line removed
text, done, err := s.Ledger.Begin(sessionID, step, cost)
if err != nil || done {
	return text, err
}
text, err = s.Provider.Transcribe(ctx, path)
if err != nil {
	var ae *APIError
	if errors.As(err, &ae) {
		return "", errors.Join(err, s.Ledger.Cancel(sessionID, step))
	}
	return "", errors.Join(fmt.Errorf("%w: %v", paidcall.ErrUncertain, err), s.Ledger.Unknown(sessionID, step))
}
_ = s.Ledger.Finish(sessionID, step, cost, text)

The ledger counts any error answer from the provider as a refusal, a 5xx included, and treats it as not billed. Whether a failed request is billed depends on the provider.

Temporal retries a paid step only after a 429 or a 5xx, answers a later attempt can change. Any other error is non-retryable and ends the step. A paid step gets a 10-minute timeout and two attempts, 30 s apart.

When a worker dies during a paid step, Temporal starts a second attempt, and that attempt asks the ledger first. What it finds depends on where the worker ended:

worker endedTemporal historyledger entrynext attempt
after Begin, before or during the provider callno completed eventpendingno call; the run ends degraded
after the provider’s reply, before Finishno completed eventpendingno call; the paid answer is lost
after Finish, before Temporal records the resultno completed eventdone, result storedthe stored result; no call

At every row, the provider gets at most one call. A pending entry returns ErrUncertain, which is non-retryable: the run is degraded, and the recording is still uploaded. The kill test below covers every row.

Two caps limit the spend, a per-recording cap and a daily cap, both set by environment variables. Begin adds the reserved cost of the step to the entries already in the ledger and refuses the request if either cap would be crossed. A pending or spent entry stays counted.

A double click on “Summarize” can also repeat a paid step. It starts two workflow runs for the same recording and step. The ledger key is the recording and the step, not the run, so the second run’s Begin makes no provider call: it gets the stored summary, or, if the first run is still waiting, a refusal. A chain test double-clicks and counts a single summary call.

A provider-side idempotency key would make the pending rule unnecessary, but not the spending caps. I found no such key in the request parameters of either provider, so the app records the calls itself. The record is a file on the worker’s own volume: one worker on one host writes it, with no network call before a paid call.

If the Docker volume is lost, the ledger loses its entries, and an interrupted step can call the provider again.

The ledger is not specific to paying: any call that must happen only once could use it, though here only the two paid steps do.

SIGKILL at nine crash points of the chain

The test starts the built worker with Temporal, NATS and MongoDB. Both providers and S3 are replaced by stand-in servers: local HTTP servers that answer only the requests the worker sends, and that can hold a request open or return an error on demand. At five points, the test sends SIGKILL (an immediate stop with no cleanup) while the stand-in server holds the request, then restarts the worker at once. The other four points need a few lines of code that only the test build contains: the worker pauses after the provider’s reply, or after Finish, and the test sends SIGKILL during the pause. Every point was tested three times. I used SIGKILL rather than a normal stop, as in the NATS post. docker stop first sends SIGTERM (Docker docs), which the worker can catch to finish or hand back its current task. The ledger exists for the crash with no clean shutdown, and SIGKILL gives the worker no chance to clean up: the paid call is left without an answer.

crash pointrecoveryoutcometranscribe callssummarize calls
worker down at publishunder 1 scomplete11
during the transcription call~50 sdegraded, outcome unknown10
during the summary call~50 sdegraded, outcome unknown11
during the upload~25 scomplete, file sent again11
after the notify5 to 10 scomplete11
after the transcription reply, before Finish~50 sdegraded, outcome unknown10
after Finish on the transcription~50 scomplete, stored transcript reused11
after the summary reply, before Finish~50 sdegraded, basic summary11
after Finish on the summary~50 scomplete, stored summary reused11

All 27 workflows ended. No paid call was made twice, and the stream kept one recording.processed event per recording. Twelve ended degraded: a kill during a paid call, or after its reply and before Finish, leaves the entry pending, and its cost stays counted. A kill right after Finish costs nothing: the next attempt gets the stored result. With no transcript, the summary step has nothing to summarize and makes no call. A crash during the upload sent the file again, which is free. The first version of the test found a slow recovery. A crash right after the transcription call started took 630 s to recover. Temporal had no way to tell a dead worker from a slow one, so it waited for the activity’s full timeout of 10 minutes, then added the 30 s retry interval. That baseline is a single trial.

Temporal’s docs recommend heartbeats for long-running activities, and I had added none. Every activity except Persist and the transcript read now sends the heartbeat described in the basics section: every 5 s, with a 20 s heartbeat timeout. The same crash recovers in about 50 s: 20 s to notice and 30 s before the retry. Without heartbeats, a crash during the upload would have waited up to 30 minutes.

A hung transcription call is ended by the HTTP client’s own 8-minute timeout (2 minutes for the summary), set under the activity’s 10 minutes.

Not covered: a crash during Persist, a duplicate notify publish, and latency from the production providers. Persist and Notify make no paid call.

Three faults around the worker

This time the worker stays up and the services around it fail. The three faults were tested on the full local stack (backend, NATS, Temporal, MongoDB, a local S3), with stand-in servers for both providers:

  • The transcription provider answered 500, then succeeded. Temporal retried 30.05 s later: two transcription calls, the first refused, the workflow not degraded.
  • Temporal was restarted with docker restart during a 60 s transcription call: one transcription call, not degraded.
  • The S3 container was stopped after the summary finished and started again 32 s later: three upload attempts failed (at +6, +16 and +28 s), the fourth succeeded, and no paid step was repeated.

A silent recording on production

The release went out with three test recordings on production, and the ledger has one transcribe and one summarize entry for each. The same day, a user recording on production was 8.3 s of near-silence (mean -37 dB). The transcription returned [background noise]. The summary model received that and answered it like a chatbot, and the answer became the recording’s summary.

A test call had hit the same problem the day before. Its input was a clean sentence that happened to contain a request, and the summary ended with “I can’t send messages”: the model replied to the request instead of summarizing it. I noted that as a side finding, not a defect. The tests caught neither case, because every empty or silent case in them used a stand-in summary server, and the only live calls before release used clean speech.

The change has two parts. A transcript with under 20 characters left after removing [...] tags gets “No speech detected” as its summary, with no call and no ledger entry, and the workflow is not degraded. The transcript now goes to the model wrapped in <transcript> tags, with a prompt that says to summarize only the text between the tags. Before the change shipped, a live call used near-silent input that gets past the guard (a tag plus dots). It answered “No content.”

Since then, each paid step gets one live call per class of input (speech, silence) before release, because a stand-in server answers the way its author expects. An odd answer from a live call now counts as a defect.

Did the recording chain need Temporal?

The app already uses NATS JetStream between its services. The NATS post describes the transcript pipeline on a plain consumer: an upsert, a message ID and a 24-hour duplicate window make a redelivered message safe. In an earlier crash test, that consumer gave the same correct result as Temporal, and it needs no extra containers. Recovery took about 40 s; with a 6 s ack wait and an in-progress heartbeat it fell to 6 to 9 s, against 5 to 9 s for Temporal. That result became my rule for this app: Temporal only for flows that meet at least four of these five criteria.

  1. Side effects that are not safe to repeat, across three or more steps (a paid API call, a delete).
  2. Waits longer than a consumer’s ack wait.
  3. A terminal failure that needs cleanup after earlier steps succeeded.
  4. State that must survive a restart or a deploy mid-flow.
  5. Someone needs to see where a given recording is.

The transcript pipeline scored 1 of 5 and stayed on NATS. The recording chain scored 4.5 of 5: criteria 1, 3, 4 and 5, and half of 2. Its steps can outlast a consumer’s ack wait, the time NATS waits for an acknowledgement before it delivers the message again. But a consumer can send an in-progress ack while it works. Each ack restarts the timer: a long step does not cause a redelivery. That score counts the upload as a third unsafe step, because it can delete the local file. That delete is off by default. Without it, criterion 1 fails and the score is 3.5, under the line of four. By default no paid step is chosen either.

NATS moves the events, Temporal drives the steps, and the ledger records the paid calls.

  • NATS carries events between services. If a consumer dies before it acknowledges an event, NATS delivers it again; a message ID and an upsert make that second delivery harmless.
  • Temporal keeps the steps in order and saves the result of every finished step. After a restart, the run continues from the last saved step, and a step that keeps failing ends the run in a known state.
  • The ledger records every paid call. Before a call, it tells the step whether the provider may already have been called; if so, the step does not call again. The ledger works without Temporal: its first version lived in the text-to-speech prototype, on a plain NATS consumer.

The rule says the default chain does not need Temporal, and I kept it anyway. The reason is the step choice. A recording can proceed with no paid step, one or both, and a user can add a step that was not chosen at the start. One workflow handles every case, with the same retries and the same saved progress. On NATS alone, I would have written that state handling myself.

Not measured: provider latency under load, and recordings processed in parallel on the production host.