The Event History: What Temporal Saves

Workflow Code Doesn't Do Things. It Asks for Them.

This is the most important idea in the whole system, and it is easy to miss.

Two separate programs are involved. Your worker process runs your workflow code, with the Temporal SDK as a library inside it. The Temporal server is a separate service with a database that holds every workflow's history. Your workflow code only talks to the SDK. The SDK talks to the server, and the server sends out the real work.

Many of these terms start with "workflow," "worker" or "task." This is what each one means here:

TermWhat it isGo analogy
Workflow function (workflow definition)The code you write that lists the steps: OrderWorkflow. It decides what happens next, but does no I/O itself.A func
Workflow (workflow execution)One run of that function, for one input, with its own ID (for example order-A-91). It can stay open for seconds or months. "The workflow is waiting" means this run.One call of the func
ActivityA normal function that does the real work: an HTTP call, a DB write, sending an email. ChargeCard is an activity. It can fail and be retried.A normal func with side effects
Temporal serverThe separate service that stores every workflow's history, holds timers, and hands out tasks. It never runs your code.Database plus job scheduler
Worker (worker process)A program you build and run, for example ./order-worker on your own servers. You register your workflow functions and activities with it. It asks the server for tasks and runs your code. One worker usually runs both workflow code and activity code.Your main() binary
SDKThe Temporal library linked into the worker. It talks to the server, runs your workflow function, and turns its requests into commands.An imported package
Task queueA named line on the server, for example "orders", where tasks wait until a worker picks them up. Workers poll it, meaning they ask "is there any work for me?"A buffered channel shared over the network
Workflow taskOne round of "here's the history so far, run the workflow function until it can't go any further, and send back commands." It takes milliseconds. A workflow that lives for 3 days may only have 5 of these.One turn of an event loop
Activity taskOne order to run one activity once, for example "run ChargeCard with this input." The worker runs it and reports the result or the error.A job pulled off a queue
CommandA request the workflow function makes through the SDK, for example ScheduleActivityTask. It only exists in the worker's memory until the workflow task ends.An item added to a slice
Event / historyWhat the server saved after accepting a command or seeing a result, for example ActivityTaskCompleted. The history is the ordered list of events for one workflow, and it is the only thing that lasts.An append-only log

There's no separate "workflow worker" or "activity worker" program by default. It's one worker process doing two kinds of tasks. When this guide says "an activity worker runs ChargeCard," it means a worker (maybe the same one, maybe another) picking up an activity task. You can split them into separate deployments, but that's your choice, not something Temporal requires.

Workflow function vs worker. Think of an HTTP server. The workflow function is like a handler, and the worker is like the server that calls it. You never call OrderWorkflow yourself. You deploy a worker binary, and it calls your functions when tasks arrive:

func main() {                                            // the worker: build, deploy, runs forever
    c, _ := client.Dial(client.Options{HostPort: "temporal:7233"})
    w := worker.New(c, "orders", worker.Options{})       // poll the "orders" task queue
    w.RegisterWorkflow(OrderWorkflow)                    // like http.HandleFunc
    w.RegisterActivity(ChargeCard)
    w.Run(worker.InterruptCh())                          // like http.ListenAndServe
}

The workflow function is code with one run per order. The worker is a running program, with as many copies as you deploy. One worker pod hosts thousands of workflow runs at once, each one a frozen goroutine, just as one web server handles thousands of requests.

func OrderWorkflow(ctx workflow.Context, order Order) error {
    fut := workflow.ExecuteActivity(ctx, ChargeCard, order)   // line A
    var receipt Receipt
    err := fut.Get(ctx, &receipt)                            // line B
    ...
}

When your workflow calls ExecuteActivity(ChargeCard), your code does not make an HTTP call, and it does not put anything on a queue. Here is what happens instead:

  1. Line A: the SDK writes down a command. "Writes down" means it adds ScheduleActivityTask{ChargeCard, order} to a plain list in the worker's memory. It does not run ChargeCard. It returns a Future, which is an empty box that will hold the result later. Nothing has left the process yet.
  2. Line B: the workflow waits. Your function doesn't run on its own. The SDK calls it, the way a test runner calls a test. The two share one thread and take turns. fut.Get() is SDK code, not a network call. It checks one thing: "Do I have the ChargeCard result yet?" The first time through, the answer is no. So Get() does not return, and your function freezes on line B with its local variables kept as they are. Now it's the SDK's turn again. A function that can freeze halfway and later carry on from the same spot is called a coroutine.
  3. "Can't go any further" means every path is frozen. On its turn, the SDK checks whether any part of your code can still move. It keeps running your code until every path in it is frozen on an empty Future, a timer or a signal. If you start three activities and then wait on all of them, the SDK writes down three commands before it hits that wall. Once it does, this round of work (one workflow task) is finished.
  4. The SDK sends the commands. This is a single gRPC call to the server, RespondWorkflowTaskCompleted, that sends the whole list of commands. In effect it says: "Here is everything this workflow wants done next."
  5. The server saves, then acts. The server saves each command as an event (for example ActivityTaskScheduled). Only then does it put a task on the ChargeCard task queue. An activity worker picks that task up and makes the real HTTP call. So the queue and the HTTP call do happen, but the server and the activity worker do them. Your workflow function does neither.
  6. The result comes back through history. The server saves ActivityTaskCompleted with the receipt and schedules a new workflow task. If the frozen function is still in the worker's memory, the SDK puts the receipt in the box and unfreezes it. Get() returns, and line C runs. If the worker crashed or dropped the workflow from memory, a worker calls the function again from the top. The SDK answers each Get() from the saved history until the code is back at line B. This is called replay.

Who is running at each moment:

time  who's running   what happens
 1    SDK             calls OrderWorkflow(order)
 2    your code       line A: ExecuteActivity → SDK writes the note, returns an empty box
 3    your code       line B: fut.Get() → "do you have the result?"
 4    SDK             "no" → your function freezes on line B
 5    SDK             sends [ScheduleActivityTask] to the server
      ... server saves it; an activity worker runs ChargeCard (the real HTTP call)
      ... server saves ActivityTaskCompleted{receipt} and tells the worker
 6    SDK             puts the receipt in the box and unfreezes your function
 7    your code       fut.Get() returns the receipt → line C runs

Freeze, Then Resume or Replay

When the code reaches Get() on an activity that hasn't finished, it is easy to get three things wrong:

  • The code after Get() isn't skipped. It just hasn't run yet. The function is frozen on line B, like a bookmark. Nothing after that line is thrown away.
  • What ends is this round, not the workflow. The current workflow task ends: the SDK sends its commands and moves on. The workflow is still open, and the server shows it as Running. It finishes only when your function returns, which sends a CompleteWorkflowExecution command.
  • The server creates the next workflow task, and it usually doesn't start from line 1. When the activity finishes, the server saves ActivityTaskCompleted and queues a new workflow task. What the SDK does next depends on whether it still has the frozen function.
CaseWhat happens
Frozen function still in the worker's cache (the common case)The SDK puts the receipt in the box and unfreezes the function at line B. Lines 1 to A do not run again.
Not in memory (crash, restart, cache eviction, or a different worker)The SDK calls the function from line 1 and replays it. At line A, ExecuteActivity sees in the history that the activity was already scheduled, so it does not schedule it again. At line B, Get() finds the receipt in the history and returns right away. Then the code runs past B for the first time.

In both cases your code ends up at the same line with the same variables. Resuming is the fast path. Replay is the backup for when the in-memory copy is gone. Replay works only because re-running lines 1 to B gives the same result every time (see Replay, Determinism).

Each step is saved on the server before it happens, so a worker crash while the workflow is paused at line B loses nothing. Any worker can run the function again and replay it to the same spot.

Why a Workflow Can Wait Three Days for Free

While a workflow waits, the history on the server is the real copy. The frozen function in the worker's memory is only a spare copy, kept to save time. Compare a normal program with a workflow:

  • Normal code: time.Sleep(72 * time.Hour) holds a thread and its memory for three days, and the process must stay up the whole time. A restart on day two loses the program's place in the code.
  • Temporal: workflow.Sleep(ctx, 72*time.Hour) doesn't sleep. Like ExecuteActivity, it only writes a command, StartTimer{72h}. The server saves it and stores a timer in its database: "wake workflow X on Friday at 10:00." Now the history (what has happened) and the timer (when to continue) are both on the server, and nothing in the worker is needed. The worker can drop the frozen function, restart or be redeployed.

"But isn't the SDK blocked?" No. Sending the commands means "I'm done with this round," and the server replies "OK" in milliseconds. The SDK does not wait for the activity or the timer. Its small pool of poller threads goes back to asking the server for any workflow task on the queue, which might belong to workflow Y or Z. When the timer fires, the server puts a new task for workflow X on the queue, and whichever poller is free picks it up. During the three days, the server does the waiting, as a timer row in its database.

Three days later, the server's timer fires. The server saves TimerFired and gives a workflow task to any worker. That worker calls the function from the top, and replay rebuilds every variable from the history. When the code reaches the Sleep line, the history says the timer already fired, so the code keeps going.

Normal sleepTemporal wait
Thread heldYes, one thread blocked for three daysNo thread waits for this workflow. The SDK's few poller threads move on to other workflows.
Worker memory usedYes, until it finishesOnly while the spare copy is cached: a parked goroutine in Go, a pooled thread in Java. It gets dropped when the cache fills.
Survives a restartNoYes
Where the wait livesYour processOne row in the server's database

That is why one cluster can hold millions of waiting workflows. Most of them are just rows in a database, not running code. The same goes for waiting on an activity, a signal or a human approval. The server saves the reason for the wait, and no worker is needed until something new happens. (Keeping the spare copy in memory is called sticky execution, see Workers and task queues. It only speeds things up.)

CommandEvent
Who creates itYour workflow code, through the SDKThe Temporal server
Saved to disk?No. It only exists in memory.Yes. It is added to the saved history.
ExamplesScheduleActivityTask, StartTimer, CompleteWorkflowExecutionActivityTaskScheduled, TimerStarted, WorkflowExecutionCompleted
Think of it asAsking the OS to write a fileThe data actually landing on disk

Your workflow only asks for things, so running it again has no side effects. Nothing gets charged or sent twice. This is what makes replay possible (see Replay). It is also why the split between workflows and activities (see Workflows vs activities) is a hard rule, not a style choice.

The Loop

A workflow moves forward one workflow task at a time. A workflow task means: "Here is the history so far. Run the code and tell me what you want to do next."

Sequence of one workflow task between three parties: the worker, which is your process; the Temporal server; and persistence. Workflow task phase: the worker long-polls the server for work. The server replies with a workflow task, which is the history so far. The worker runs the workflow function from line 1 until it blocks on something not yet in history, then sends back commands, for example ScheduleActivityTask. The server appends WorkflowTaskCompleted plus one event per command to persistence. Activity phase: the server dispatches the activity task to a worker; the worker returns the activity result; the server appends ActivityTaskCompleted plus the next WorkflowTaskScheduled. That next workflow task repeats the loop until a command closes the workflow. Between workflow tasks the workflow is not running anywhere; it exists only as rows in the database.
One workflow task: history in, commands out, events appended Your code only produces commands. The server turns them into saved events and real work.

Between workflow tasks, your workflow is not running anywhere. It exists only as rows in a database. That is why a 30-day sleep costs nothing (see Timers). It is also why it's normal to have a hundred times more workflows than workers.

What a Real History Looks Like

Here is the order workflow from the What Temporal is part. The card charge has gone through, and the workflow has started its 30-day sleep. Each line is a row that never changes. The number on the left is the event ID, which only goes up within one workflow run:

 1  WorkflowExecutionStarted      input: {orderID: "A-91"}
 2  WorkflowTaskScheduled         task queue: "orders"
 3  WorkflowTaskStarted           worker: host-7 (identity)
 4  WorkflowTaskCompleted         → produced 1 command
 5  ActivityTaskScheduled         ChargeCard, attempt 1
 6  ActivityTaskStarted           worker: host-2
 7  ActivityTaskFailed            "gateway 503"
 8  ActivityTaskScheduled         ChargeCard, attempt 2   (retry)
 9  ActivityTaskStarted           worker: host-9
10  ActivityTaskCompleted         result: {chargeID: "ch_77"}
11  WorkflowTaskScheduled
12  WorkflowTaskStarted
13  WorkflowTaskCompleted         → produced 2 commands
14  ActivityTaskScheduled         ReserveInventory
15  ...
22  TimerStarted                  30d, timerID: 1
        ← the workflow now exists only here, on disk

Notice three things. Each one comes up again later in the guide.

  1. The retry is in the history (events 7–10). Retries don't happen silently inside your process. Each attempt is a saved event you can look at. So you can answer "how many times did this charge fail last Tuesday?" without adding any logging.
  2. The result is saved (event 10). {chargeID: "ch_77"} stays in the history for good. A month later, a replay can give your charge variable this value without charging the card again.
  3. Each WorkflowTaskCompleted marks a boundary. Everything the workflow decided in that task was saved together, all at once. So the history is a log of decisions. Replaying it makes exactly the same decisions again, as long as your code follows the rules in the Determinism part.
  • Guarantees: Events are only ever added, never changed. Each workflow run's events are in one fixed order. An event is saved before any work it triggers is sent out. So anything that happened can be recovered from the history.
  • Does not guarantee: That your in-memory values are saved. A value survives only if it was a workflow input, an activity result, or a signal payload. Anything else is simply worked out again by re-running your code.