Imagine someone places an order, say "order 4512", and gets charged twice. They raise a ticket, and an AI agent reviews it. It checks the ledger of entries and notices that the charge for the same order ID is stored twice. A good practice that payment providers follow is that they maintain an append-only ledger, where entries cannot be edited or removed. The refundable amount is not stored but calculated from that ledger.
The agent makes a request to the provider to refund the amount, the refund is processed, and the provider sends a response back to our server. But the network blips or something happens, which makes the response not reach the server. What now? The server does not know if the request never reached the provider or the response never came. It can follow at-most-once delivery (but it can risk never processing the refund) or at-least-once delivery (but risk processing the refund twice and losing money). For such scenarios, payment providers accept an idempotency key to deduplicate the requests in case the server retries. The idempotency key is what makes at-least-once delivery safe. If the request reaches once, the idempotency key is stored on the provider side; it processes the refund and sends a 201. If the same request is retried, the provider finds the same stored key, creates nothing, and returns the original refund to the server with a 200.
The 200 is the choice of the mock provider that I wrote. It is in the same repository I linked below. Stripe, on the other hand, replays the original status code and body, and gives a 409 status if a request with the same key is still in progress, and returns an idempotency error if the same key is reused with different params.
In this post we will actually learn how a durable execution engine works, by understanding how I built one. My build was supported by 2 very cool tools by Upstash, Upstash Redis and QStash, and both of those links go straight to their docs. The code for all of it is in my GitHub, in the durable-refund-agent repository.
What is an agent
We want to design our system in a way that every refund request is first checked by an AI agent. For a certain amount, the agent processes the ticket end to end; otherwise, a human takes over. We will walk through a failure-resistant design for this system in this article.
An agent is a simple loop to and from an LLM. The LLM replies with whatever it needs, and the agent provides it. The agent keeps the model updated and acts as per the LLM's instructions. When the LLM does not require anything else, the agent stops, and our ticket is processed.
The LLM is only capable of producing text, so it cannot see the ledger or our orders DB. It can only "ask" someone to do it. That is where the agent comes in. The LLM asks what it needs, and then our code runs the functions and the agent gives back the results to the model. This process continues.
The refund agent loop looks like this:
| Turn | LLM asks for | Our code does | Result |
|---|---|---|---|
| 1 | get_order("4512") |
reads the orders database | ₹1,500 · headphones · paid |
| 2 | list_charges("4512") |
GET /charges on the provider |
ch_1 ₹1,500 · ch_2 ₹1,500 |
| 3 | get_refund_policy() |
returns the policy text | only the surplus is refundable; above ₹2,000 needs approval |
| 4 | issue_refund("ch_2", 150000) |
POST /refunds on the provider |
rf_1 created · ₹1,500 |
| 5 | send_email(...) |
sends the customer an email | sent |
| 6 | nothing | stops the loop | "refunded the duplicate ₹1,500" |
The message list goes out every time to the model, with the new messages and replies appended. In between turns the model does not retain anything, and hence we say the model is stateless and it needs every part of the conversation again on every turn. This list is stored in RAM by our process. And so, a single crash can lead to the agent losing all the progress it made. We will see how.
Building the agent
I wrote out what a tool should look like first. It has three important fields: Description, Parameters and Run. Run is how the tool actually functions and we define it for each tool, like, get_order fetches every detail we need about an order from the SQLite DB.
// Tool is one function the model may ask for.
type Tool struct {
Name string
// the model's understanding of what the tool does
Description string
// json schema for the tool's arguments
Parameters json.RawMessage
// decodes the args and returns the result the model reads
Run func(ctx context.Context, args json.RawMessage) (string, error)
}
We need to define parameters correctly and carefully. For the issue_refund tool, we make sure that it is amount_paise and not just amount. If it were amount, the model would have asked to refund, say, 1000 rupees, but our service would have taken it for 1000 paise and refunded 10 rupees.
Also, the required parameters are something to think hard about. The list should include parameters we cannot afford to decode as a trivial value (0 for an absent number, and an empty string for a null or absent string). Like, if we miss amount_paise, the decoded amount would come out to be zero. (Although I handle this scenario in code, the required params are still very important to be chosen carefully.)
Parameters: json.RawMessage(`{"type":"object","properties":{"charge_id":{"type":"string","description":"the charge to refund, for example ch_2"},"amount_paise":{"type":"integer","description":"how much to refund, in paise, so 1500 rupees is 150000"}},"required":["charge_id","amount_paise"]}`),
The structure of an agent is like this:
type Agent struct {
llm *llm.Client
tools *tools.Registry
}
The agent loop:
func (a *Agent) Run(ctx context.Context, ticket string) (string, error) {
msgs := []llm.Message{llm.System(SystemPrompt), llm.User(ticket)}
defs := defsFor(a.tools)
temp := 0.0
for turn := 1; turn <= maxTurns; turn++ {
resp, err := a.llm.Complete(ctx, llm.ChatRequest{
Messages: msgs,
Tools: defs,
Temperature: &temp,
})
if err != nil {
return "", fmt.Errorf("turn %d: %w", turn, err)
}
reply, ok := resp.Reply()
if !ok {
return "", fmt.Errorf("turn %d: the model returned no choices", turn)
}
msgs = append(msgs, reply)
if len(reply.ToolCalls) == 0 {
return reply.Content, nil
}
for _, c := range reply.ToolCalls {
result, err := a.call(ctx, c)
if err != nil {
return "", fmt.Errorf("turn %d: %s: %w", turn, c.Function.Name, err)
}
msgs = append(msgs, llm.ToolResult(c.ID, c.Function.Name, result))
}
}
return "", fmt.Errorf("gave up after %d turns, last called %s", maxTurns, lastTool(msgs))
}
See how the msgs slice keeps growing. First it was a system prompt and a ticket, then it gets appended with every LLM reply and every tool result. And it has to be resupplied every time. A tool message has to be mandatorily preceded by an assistant message carrying tool_calls (tool calls are checked from the model's reply), else the conversation will be malformed and the LLM API rejects the next request. We return when:
The LLM reply has no mention of a tool call. This means it does not need our agent to supply anything anymore. We can consider it the final answer and return.
We cross the cap of 10 calls. The model is genuinely confused if it takes this long. If we do not cap it at 10 calls, our bill can give us nightmares. (Later I raised the cap to 30, because I wanted to test it against a real LLM with multiple orders.)
Something actually breaks. Like an SQL syntax error, the DB not responding, or the model call itself failing.
It works if we run this (you can see the README for how to run various stuff).
curl -X POST localhost:8080/tickets -H 'Content-Type: application/json' \
--data '{"message":"i was charged twice for order 4512"}'
{"answer":"Refunded the duplicate charge of ₹1500.00 on order 4512.","req":"MWH3OFRL"}
level=INFO msg="ticket received" req=MWH3OFRL chars=35
level=INFO msg="email sent" to_domain=example.com chars=47
level=INFO msg="ticket done" req=MWH3OFRL took=12.032108041s
We use
--timeout 60shere so the first demo runs flawlessly.
The agent does everything right from reading the order, checking the ledger, refunding in accordance with the policy and emailing the customer. Everything is working perfectly. But we talked about how one crash can break it. Let us see how!
Every serverless platform has a timeout. Let's give our agent one as well.
go run ./cmd/provider --addr :8081 --allow-over-refunds
go run ./cmd/mockllm --addr :8082 --delay 2s
go run ./cmd/seed --db orders.db --provider http://localhost:8081
go run ./cmd/agent --addr :8080 --db orders.db --provider http://localhost:8081 \
--llm http://localhost:8082/v1 --timeout 10s
The mock LLM takes 2s to answer. And how many calls does our agent make to the model? It is 6 calls. So the timeout would hit during the 5th call, i.e. before the send_email step ever runs.
curl -X POST localhost:8080/tickets -H 'Content-Type: application/json' \
--data '{"message":"i was charged twice for order 4512"}'
{"error":"the agent ran out of time","req":"64BH5APA"}
We hit the timeout. The client does not know what happened or how far the agent got. So it would simply retry. (Every retrying proxy in this universe does exactly that.)
We again get:
{"error":"the agent ran out of time","req":"H36XF46N"}
Let's look at the ledger.
{"id":"ch_1","kind":"charge","order_id":"4512","amount_paise":150000}
{"id":"ch_2","kind":"charge","order_id":"4512","amount_paise":150000}
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2","amount_paise":150000}
{"id":"rf_2","kind":"refund","order_id":"4512","charge_id":"ch_2","amount_paise":150000}
ch_2 was charged ₹1,500 and refunded ₹3,000. The customer was also emailed zero times, because both runs died in the send_email model call.
Starting with our durable execution engine
We saw how our whole agent loop fails when a single timeout ruins our whole progress. If the agent has progressed to a point, and then the run times out, in the next run, the agent has to start from the very beginning. But what if we can save the progress of each step, and when the agent runs next, it does not have to rerun the functions again because the results of the steps executed previously are already available.
We have a Ctx struct for our execution engine. And I named my engine justonce. So whenever in the future, I refer to our "durable execution engine", I will just be calling it justonce.
type Ctx struct {
RunID string
store Store // an interface; Get and Set for now, a lock later
mu sync.Mutex
seen map[string]bool
}
Ctx is the handle for a single run, and every invocation of a run (fresh or replay) is allocated a Ctx. Ctx keeps track of the step names (using the claim method) used in this run, so that we do not have duplicates. This is very important as we do not want to replay the result of another step.
Here is what the claim method looks like.
func (c *Ctx) claim(name string) error {
c.mu.Lock()
defer c.mu.Unlock()
if c.seen[name] {
return fmt.Errorf("justonce: run %s step %s has already been claimed", c.RunID, name)
}
c.seen[name] = true
return nil
}
The most important function in our engine is Step. It takes a context.Context, a Ctx, a name and a function (which returns a generic T) and returns a generic T.
We first check if the step already has the result stored. If there is something saved, we do not run the function. This is the important part of the engine.
func Step[T any](ctx context.Context, c *Ctx, name string, fn func() (T, error)) (T, error) {
var zero T
if name == "" {
return zero, fmt.Errorf("justonce: a step in run %s has no name", c.RunID)
}
if err := c.claim(name); err != nil {
return zero, err
}
raw, ok, err := c.store.Get(ctx, c.RunID, name)
if err != nil {
return zero, fmt.Errorf("justonce: run %s step %s: %w", c.RunID, name, err)
}
if ok {
var result T
if err := json.Unmarshal(raw, &result); err != nil {
return zero, fmt.Errorf("justonce: run %s step %s: stored result is corrupt: %w", c.RunID, name, err)
}
return result, nil
}
// ...
}
If we do not find anything stored, this is probably the first run, and we run the function, store the results and return.
The side effect has already occurred when fn() returns and we cannot afford not to save it. (If the refund has been given, we HAVE to save it.) That is why we pass a context which cannot be cancelled to the Set method. The parent's deadline is also dropped, and so we specify our own.
const saveTimeout = 5 * time.Second
// ...
out, err := fn()
if err != nil {
return zero, err
}
saved, err := json.Marshal(out)
if err != nil {
return zero, fmt.Errorf("justonce: encoding step %s of run %s: %w", name, c.RunID, err)
}
saveCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), saveTimeout)
defer cancel()
if err := c.store.Set(saveCtx, c.RunID, name, saved); err != nil {
return zero, fmt.Errorf("justonce: saving step %s of run %s: %w", name, c.RunID, err)
}
return out, nil
}
fn does not take a context.Context as an argument. Step takes it, and uses it for Get and a modified form for Set. We do not know what work the fn closure does. We would need to know the biggest deadline to pass context.Context to the closure, but we do not (unlike the Set method, where we do). The save cancellation is not free, as we cannot throw away what the closure returns.
The store is in-memory. The Get and Set methods:
func (m *MemoryStore) Get(_ context.Context, runID, step string) (json.RawMessage, bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
raw, ok := m.steps[key(runID, step)]
return raw, ok, nil
}
func (m *MemoryStore) Set(_ context.Context, runID, step string, result json.RawMessage) error {
m.mu.Lock()
defer m.mu.Unlock()
// copied: a RawMessage is a slice and the caller still holds the original.
m.steps[key(runID, step)] = append(json.RawMessage(nil), result...)
return nil
}
func key(runID, step string) string { return runID + ":" + step }
We now wire our engine to the agent loop. We take the Ctx we wrote as an argument, and wrap the model call with the Step function.
func (a *Agent) Run(ctx context.Context, engine *justonce.Ctx, ticket string) (string, error) {
// the same msgs slice and tool defs as before
for turn := 1; turn <= maxTurns; turn++ {
// llm-turn
resp, err := justonce.Step(ctx, engine, fmt.Sprintf("llm-%d", turn),
func() (llm.ChatResponse, error) {
return a.llm.Complete(ctx, llm.ChatRequest{
Messages: msgs,
Tools: defs,
Temperature: &temp,
})
})
if err != nil {
return "", fmt.Errorf("turn %d: %w", turn, err)
}
// ...
}
}
We do the same for the tool call.
for i, c := range reply.ToolCalls {
// tool-turn-i
result, err := justonce.Step(ctx, engine, fmt.Sprintf("tool-%d-%d", turn, i),
func() (string, error) { return a.call(ctx, c) })
if err != nil {
return "", fmt.Errorf("turn %d: %s: %w", turn, c.Function.Name, err)
}
msgs = append(msgs, llm.ToolResult(c.ID, c.Function.Name, result))
}
The step name is built in such a way that it comes out identical on every retry.
The driver code (the main for agent, mockllm, provider and seed) can be found in the repository, again.
The run_id has to be supplied by the client, else the server will mint one itself and every retry would mean a different run, and every step will rerun. POST /tickets requires it mandatorily.
Where the in-memory store fails
I have added a replay and run count in Ctx to see stats for the demo. We set all services up.
go run ./cmd/provider --allow-over-refunds
go run ./cmd/mockllm --delay 2s
go run ./cmd/seed
go build -o ./bin/agent ./cmd/agent && ./bin/agent --timeout 10s
Let us run three scenarios. The first one is like this:
$ curl ... -d '{"run_id":"r1","message":"i was charged twice for order 4512"}'
{"error":"the agent ran out of time","req":"3CPSR3QD","run":"r1"}
HTTP 504 in 10.003837s
$ curl ... -d '{"run_id":"r1","message":"i was charged twice for order 4512"}'
{"answer":"Refunded the duplicate charge of ₹1500.00 on order 4512.","req":"BUVVTPUA","run":"r1"}
HTTP 200 in 4.004375s
level=ERROR msg="ticket ran out of time" req=3CPSR3QD run=r1 replayed=0 ran=8 took=10.001161292s
level=INFO msg="ticket done" req=BUVVTPUA run=r1 replayed=8 ran=3 took=4.003954084s
{"id":"ch_1","kind":"charge","order_id":"4512","amount_paise":150000}
{"id":"ch_2","kind":"charge","order_id":"4512","amount_paise":150000}
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2","amount_paise":150000}
Here, the loop again times out. It runs 8 steps and replays 0. On the retry, it succeeds, replaying the 8 that already ran and running the remaining 3 for the first time.
These are the steps:
| # | step | what it does |
|---|---|---|
| 1 | llm-1 |
model asks for the order |
| 2 | tool-1-0 |
get_order reads order 4512 from sqlite |
| 3 | llm-2 |
model asks for the charges |
| 4 | tool-2-0 |
list_charges gets ch_1 and ch_2 from the provider |
| 5 | llm-3 |
model asks for the policy |
| 6 | tool-3-0 |
get_refund_policy returns a constant |
| 7 | llm-4 |
model asks to refund ch_2
|
| 8 | tool-4-0 |
issue_refund moves the money, provider creates rf_1
|
| 9 | llm-5 |
model asks to send the email |
| 10 | tool-5-0 |
send_email logs the domain and the length |
| 11 | llm-6 |
model writes the final answer |
Both attempts hit the same process, so they share the same map. That is a thing to keep in mind. What if we kill the process and then retry?
level=ERROR msg="ticket ran out of time" req=IJM6OCAX run=r2 replayed=0 ran=8 took=10.001201625s
# kill -9, start again
level=ERROR msg="ticket ran out of time" req=W3SYDLGR run=r2 replayed=0 ran=8 took=10.001317084s
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2","amount_paise":150000}
{"id":"rf_2","kind":"refund","order_id":"4512","charge_id":"ch_2","amount_paise":150000}
As we know, two processes do not share the map, so when process A got killed, its map went with it, and process B starts from scratch again. The refund was saved but in process A's map that went with it, and hence it ends up refunding twice.
There is one more scenario:
$ curl ... localhost:8390/tickets -d '{"run_id":"r3",...}'
{"error":"the agent ran out of time","req":"SNLBAH2B","run":"r3"}
HTTP 504 in 10.003884s
$ curl ... localhost:8395/tickets -d '{"run_id":"r3",...}'
{"error":"the agent ran out of time","req":"V5YM4ITW","run":"r3"}
HTTP 504 in 10.004629s
# instance two
level=INFO msg="ticket received" req=V5YM4ITW run=r3
level=ERROR msg="ticket ran out of time" req=V5YM4ITW run=r3 replayed=0 ran=8 took=10.0011765s
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2","amount_paise":150000}
{"id":"rf_2","kind":"refund","order_id":"4512","charge_id":"ch_2","amount_paise":150000}
We make the same request twice with the same run id, against two instances. They are two different processes and no process was killed. Both processes have different maps, and hence double refund.
Fixing it with Upstash Redis
We saw how every process having its own map cannot really share the recorded answer with another process. We need something shared that is independent of the process. We use Redis for this. Upstash Redis provides us with a cloud hosted Redis database. Go ahead and get a connection string (Upstash console).
We use github.com/redis/go-redis/v9 as our redis client. Our Step mechanism is correct. Now, instead of the in-memory store, we write a redis store:
type RedisStore struct {
rdb *redis.Client
ttl time.Duration
}
The Get and Set methods are like this:
func (s *RedisStore) Get(ctx context.Context, runID, step string) (json.RawMessage, bool, error) {
raw, err := s.rdb.Get(ctx, stepKey(runID, step)).Bytes()
// If the key is not present in redis
if errors.Is(err, redis.Nil) {
return nil, false, nil
}
if err != nil {
return nil, false, fmt.Errorf("redis get %s: %w", stepKey(runID, step), err)
}
return json.RawMessage(raw), true, nil
}
We set with an expiry, so a step result expires at some point in time.
func (s *RedisStore) Set(ctx context.Context, runID, step string, result json.RawMessage) error {
if err := s.rdb.Set(ctx, stepKey(runID, step), []byte(result), s.ttl).Err(); err != nil {
return fmt.Errorf("redis set %s: %w", stepKey(runID, step), err)
}
return nil
}
I wire it in the agent. And on running the last 2 scenarios again:
attempt 1 504 in 10.005444s
req=4IJDGUEX replayed=0 ran=8 took=10.001410667s
kill -9, new process
attempt 2, same run id 200 in 4.340044s
req=6RS34VDK replayed=8 ran=3 took=4.339015291s
This time the steps are saved, and the saved results are replayed. What happened? This time Step does not look for the answer in the dead map, but in Redis. And only one refund is processed.
{"id":"ch_1","kind":"charge","order_id":"4512"}
{"id":"ch_2","kind":"charge","order_id":"4512"}
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2"}
If we run the two-instance scenario:
attempt 1 against :8890 (instance one) 504 in 10.004677s
req=R2BTSU6U replayed=0 ran=8 took=10.001327375s
attempt 2 against :8895 (instance two) 200 in 4.326395s
req=MH2BN2I4 replayed=8 ran=3 took=4.325367583s
{"id":"ch_1","kind":"charge","order_id":"4512"}
{"id":"ch_2","kind":"charge","order_id":"4512"}
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2"}
It works here as well!
Our step names are deterministic. Had they depended on the clock, or a random number, the Redis key or even the key for the in-memory map would have been different, and every time the read would miss, the runs would not converge, creating one refund on every attempt (this is a silent failure and replayed=0 is our only hint). This helps us to look the result up deterministically for a step when the engine runs again.
We depend on names for the determinism of our engine and our engine would not know if it is a changed name or a step that never ran at all. It is always treated like it is the first time the step runs. Temporal actually saves the sequence of the run of a workflow and compares it against the sequence of the modified flow, and if there is a drift, it throws a nondeterminism error.
More than half of system design is small careful work!
The refund that was never saved
Let us say that the provider is really slow. It records the refund but then stalls. We get the timeout before receiving the response from the provider. Let us reproduce this.
go run ./cmd/provider --allow-over-refunds --slow-refunds 8s
go run ./cmd/mockllm
go run ./cmd/seed
./bin/agent --timeout 5s
We take 3 attempts.
for i in 1 2 3; do
curl -s -w ' <- %{http_code}\n' -X POST localhost:8080/tickets \
-H 'content-type: application/json' \
-d '{"run_id":"r4","message":"i was charged twice for order 4512"}'
done
And get timed out every time because the provider is slow.
{"error":"the agent ran out of time","req":"OEZSQXPR","run":"r4"}
<- 504
{"error":"the agent ran out of time","req":"G6G4QFV3","run":"r4"}
<- 504
{"error":"the agent ran out of time","req":"PP2OJODE","run":"r4"}
<- 504
7 steps are saved on the first attempt and replayed on both the retries, but the refund step is never saved.
level=ERROR msg="ticket ran out of time" req=OEZSQXPR run=r4 replayed=0 ran=7 took=5.00384325s
level=ERROR msg="ticket ran out of time" req=G6G4QFV3 run=r4 replayed=7 ran=0 took=5.001455042s
level=ERROR msg="ticket ran out of time" req=PP2OJODE run=r4 replayed=7 ran=0 took=5.00132175s
And so there are 2 duplicate refunds in the ledger.
{"id":"ch_1","kind":"charge","order_id":"4512"}
{"id":"ch_2","kind":"charge","order_id":"4512"}
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2"}
{"id":"rf_2","kind":"refund","order_id":"4512","charge_id":"ch_2"}
{"id":"rf_3","kind":"refund","order_id":"4512","charge_id":"ch_2"}
Why did this happen? It is because the server never got a response back for any of the refunds and so it did not save it in Redis. We have to be well prepared for this scenario. As we discussed in the beginning, we send an idempotency key to the provider to avoid this scenario. Let us see that part of the code.
In the issue_refund tool, there is this part of the code from the Run:
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "refund:"+rand.Text())
Every time, the idempotency key here is built as a fresh random text. It is non-deterministic, the thing we are fighting against this whole time. We need to establish the fact that this is the same refund request using a deterministic idempotency key.
Let us move where the key comes from. Say we build the key from "refund:" + chargeID + ":" + amount. But it would not be right, because, what if user is actually required to be refunded twice (partial refunds each time). Say 750 rupees each time, for different reasons. Both would be identified as same refund attempt, and the idempotency mechanism will deduplicate and not let the second refund occur.
So we will key on step and build it from {runID}:{stepName}. Run ID and Step name are same in every retry, and they are different for different steps and different runs. Those two partial refunds are two steps, tool-4-0 and tool-4-1, so they have two different keys. And if a second refund is requested on run2, it would be different from the first refund request.
We derive the key like this. In the issue_refund tool:
key, ok := StepKeyFrom(ctx)
if !ok {
return "", errors.New("issue_refund: no step key in context")
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", "refund:"+key)
We extract the step key from context.Context. Actually there are two functions for helping us with this:
This extracts the step key from context.Context
func StepKeyFrom(ctx context.Context) (string, bool) {
k, ok := ctx.Value(stepKeyCtx{}).(string)
return k, ok && k != ""
}
And this returns a context.Context with the step key injected in it.
func WithStepKey(ctx context.Context, key string) context.Context {
return context.WithValue(ctx, stepKeyCtx{}, key)
}
We use it in our agent loop like this:
for i, c := range reply.ToolCalls {
name := fmt.Sprintf("tool-%d-%d", turn, i)
result, err := justonce.Step(ctx, engine, name,
func() (string, error) { return a.call(tools.WithStepKey(ctx, engine.RunID+":"+name), c) })
if err != nil {
return "", fmt.Errorf("turn %d: %s: %w", turn, c.Function.Name, err)
}
msgs = append(msgs, llm.ToolResult(c.ID, c.Function.Name, result))
}
I think we have the fix. Let us run the scenario again.
go run ./cmd/provider --allow-over-refunds --slow-refunds 8s
go run ./cmd/mockllm
go run ./cmd/seed
./bin/agent --timeout 5s
for i in 1 2 3; do
curl -s -w ' <- %{http_code}\n' -X POST localhost:8080/tickets \
-H 'content-type: application/json' \
-d '{"run_id":"r5","message":"i was charged twice for order 4512"}'
done
See how the latter 2 retries do not time out. Why? The first retry sends the same key, and the provider sends the response for the refund it has already processed. This step gets saved in Redis and so the second retry does not even reach the provider and it replays the refund and later steps.
{"error":"the agent ran out of time","req":"D3HAN3CI","run":"r5"}
<- 504
{"answer":"Refunded the duplicate charge of ₹1500.00 on order 4512.","req":"6QNNWLP3","run":"r5"}
<- 200
{"answer":"Refunded the duplicate charge of ₹1500.00 on order 4512.","req":"3UBR6LA4","run":"r5"}
<- 200
level=ERROR msg="ticket ran out of time" req=D3HAN3CI run=r5 replayed=0 ran=7 took=5.00127225s
level=INFO msg="ticket done" req=6QNNWLP3 run=r5 replayed=7 ran=4 took=384.062292ms
level=INFO msg="ticket done" req=3UBR6LA4 run=r5 replayed=11 ran=0 took=279.983209ms
The ledger only shows one refund. So we are successful!
{"id":"ch_1","kind":"charge","order_id":"4512"}
{"id":"ch_2","kind":"charge","order_id":"4512"}
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2"}
Two attempts at the same time
Have we fixed everything? What if the same refund request reaches the provider at the same time? We expect it to go wrong here and get the customer refunded twice because if it reaches at the same millisecond, the provider can create the refund for both in parallel (Although, this is not possible in the mock provider as of now).
Let's see :
go run ./cmd/provider --allow-over-refunds
go run ./cmd/mockllm
go run ./cmd/seed
./bin/agent --timeout 60s
for i in 1 2; do
curl -s -w ' <- %{http_code}\n' -X POST localhost:8080/tickets \
-H 'content-type: application/json' \
-d '{"run_id":"r6","message":"i was charged twice for order 4512"}' &
done
wait
The requests have to overlap to reproduce this bug.
{"answer":"Refunded the duplicate charge of ₹1500.00 on order 4512.","req":"2ZFGURPN","run":"r6"}
<- 200
{"answer":"Refunded the duplicate charge of ₹1500.00 on order 4512.","req":"F5AWJ4DG","run":"r6"}
<- 200
The ticket is received at the exact same time. Although, the refund is created once, because our mock provider serializes the refund requests with the help of a mutex (you can see the implementation in the code), the email gets sent twice.
The 7 steps are run twice, which includes a write (a world changing request of sending the email). Do we also need to key it? What if there is another such write introduced the next day? It would be like a coin flip then. We will talk about this fix later.
level=INFO msg="ticket received" req=2ZFGURPN run=r6
level=INFO msg="ticket received" req=F5AWJ4DG run=r6
level=INFO msg="email sent" to_domain=example.com chars=47
level=INFO msg="email sent" to_domain=example.com chars=47
level=INFO msg="ticket done" req=2ZFGURPN run=r6 replayed=0 ran=11 took=607.495208ms
level=INFO msg="ticket done" req=F5AWJ4DG run=r6 replayed=4 ran=7 took=616.401083ms
{"id":"ch_1","kind":"charge","order_id":"4512"}
{"id":"ch_2","kind":"charge","order_id":"4512"}
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2"}
But what if the provider processes requests in parallel and there is no serialization? We have a racy implementation as well. And of course in that case, the customer is refunded twice.
go run ./cmd/provider --allow-over-refunds --racy-idempotency # the flag
go run ./cmd/mockllm
go run ./cmd/seed
./bin/agent --timeout 60s
for i in 1 2; do
curl -s -w ' <- %{http_code}\n' -X POST localhost:8080/tickets \
-H 'content-type: application/json' \
-d '{"run_id":"r7","message":"i was charged twice for order 4512"}' &
done
wait
{"answer":"Refunded the duplicate charge of ₹1500.00 on order 4512.","req":"MHXXELNI","run":"r7"}
<- 200
{"answer":"Refunded the duplicate charge of ₹1500.00 on order 4512.","req":"6CSQH7QS","run":"r7"}
<- 200
level=INFO msg="ticket received" req=MHXXELNI run=r7
level=INFO msg="ticket received" req=6CSQH7QS run=r7
level=INFO msg="email sent" to_domain=example.com chars=47
level=INFO msg="email sent" to_domain=example.com chars=47
level=INFO msg="ticket done" req=MHXXELNI run=r7 replayed=0 ran=11 took=740.325625ms
level=INFO msg="ticket done" req=6CSQH7QS run=r7 replayed=3 ran=8 took=763.45675ms
And here it is. We have double refunds again. Real providers avoid this and atomicity is the whole feature. But still, we want to keep our side of the system correct.
{"id":"ch_1","kind":"charge","order_id":"4512"}
{"id":"ch_2","kind":"charge","order_id":"4512"}
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2"}
{"id":"rf_2","kind":"refund","order_id":"4512","charge_id":"ch_2"}
Taking a lock on the run
The fix for this is: let a request claim a lock. Same run cannot be fired concurrently. We use Redis for this. (The in-memory store also implements these functions as it implements the same interface)
SET NX PX sets the lock for a key with an expiry atomically. (Redis commands are atomic and so we do not need a lua script here as it is just one command)
func lockKey(runID string) string { return "run:" + runID + ":lock" }
func (s *RedisStore) TryLock(ctx context.Context, runID, token string, ttl time.Duration) (bool, error) {
ok, err := s.rdb.SetNX(ctx, lockKey(runID), token, ttl).Result()
if err != nil {
return false, fmt.Errorf("redis lock %s: %w", lockKey(runID), err)
}
return ok, nil
}
For releasing the lock, we would need a lua script (as the script runs atomically). It is because we have to perform two operations, checking if the lock is still acquired by us and if it is, deleting the key.
var releaseLock = redis.NewScript(`
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
end
return 0
`)
func (s *RedisStore) Unlock(ctx context.Context, runID, token string) error {
if err := releaseLock.Run(ctx, s.rdb, []string{lockKey(runID)}, token).Err(); err != nil {
return fmt.Errorf("redis unlock %s: %w", lockKey(runID), err)
}
return nil
}
In the driver code of the agent, we take the lock like this. (You can see the full implementation in the code)
//handleTicket function
token := rand.Text()
locked, err := s.store.TryLock(ctx, req.RunID, token, s.lockTTL)
if err != nil {
// 500, we could not even ask for the lock
return
}
if !locked {
// 409 (we do not wait for the lock to be released; it has to be retried)
log.Warn("run is already in flight, refusing")
writeJSON(w, http.StatusConflict, map[string]string{"error": "this run is already being worked on"})
return
}
defer func() {
// release the lock. this context is very likely already cancelled by now
// (same as saving the side-effect of refund)
rctx, rcancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer rcancel()
if err := s.store.Unlock(rctx, req.RunID, token); err != nil {
log.Error("could not release the run lock", "err", err, "ttl", s.lockTTL)
}
}()
And now, if we run the demo again :
go run ./cmd/provider --allow-over-refunds --racy-idempotency
go run ./cmd/mockllm
go run ./cmd/seed
./bin/agent --timeout 60s
Two parallel attempts.
for i in 1 2; do
curl -s -w ' <- %{http_code}\n' -X POST localhost:8080/tickets \
-H 'content-type: application/json' \
-d '{"run_id":"r8","message":"i was charged twice for order 4512"}' &
done
wait
As the first attempt acquires the lock, the second one does not run concurrently with it.
{"error":"this run is already being worked on","req":"DLBBJNHK","run":"r8"}
<- 409
{"answer":"Refunded the duplicate charge of ₹1500.00 on order 4512.","req":"ISY7R7FW","run":"r8"}
<- 200
Only one run. One refund. One email.
level=INFO msg="ticket received" req=ISY7R7FW run=r8
level=INFO msg="ticket received" req=DLBBJNHK run=r8
level=WARN msg="run is already in flight, refusing" req=DLBBJNHK run=r8
level=INFO msg="email sent" to_domain=example.com chars=47
level=INFO msg="ticket done" req=ISY7R7FW run=r8 replayed=0 ran=11 took=704.835458ms
{"id":"ch_1","kind":"charge","order_id":"4512"}
{"id":"ch_2","kind":"charge","order_id":"4512"}
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2"}
Only one side of the email thing is fixed, i.e. no email can be sent twice concurrently. But what if the server does not receive the response after an email is sent. It is not saved in Redis, and a sequential retry can resend it. We use the same idempotency key (deterministic) fix. See the repository for implementation.
Driving the run with QStash
We always retry ourselves. We need to make that process automatic. We will use Upstash's QStash for this. It is a push-based message queue that calls HTTP endpoints and provides us with retries and at-least-once delivery.
What we will build :
POST /ticketswill create the run and publish a message. It returns with therun_idimmediately and it does not concern itself with any deadline.QStash posts to
POST /runs/continue. The endpoint acquires a lock for the run and runs the agent loop. If the deadline is hit before the run is completed, we make the endpoint publish another message and return a 200. If there is a response that is not 2XX, QStash retries and gives up after 3 retries.
Get the QStash credentials and strings from the QStash console.
QSTASH_TOKEN=
QSTASH_CURRENT_SIGNING_KEY=
QSTASH_NEXT_SIGNING_KEY=
PUBLIC_URL=https://your-tunnel.example
| What it is | |
|---|---|
QSTASH_TOKEN |
It is the publishing credential. |
QSTASH_CURRENT_SIGNING_KEY |
It verifies the Upstash-Signature on an incoming request. |
QSTASH_NEXT_SIGNING_KEY |
It is used if the current does not work. |
PUBLIC_URL |
Our endpoint which QStash calls (and obviously it cannot be localhost) |
QSTASH_URL is optional, so for the demo it is not really needed. It is the address we publish to, and the SDK already defaults to https://qstash.upstash.io. The one time you do set it is to run QStash locally: npx @upstash/qstash-cli dev gives you a QStash of your own that prints its token and both signing keys on startup, and then you point QSTASH_URL at that. It listens on port 8080 by default, which is also the agent's port, so one of the two has to move.
I implement the queue to publish the messages using QStash, and here is how the implementation looks (see the repo, for full detail).
type runPublisher struct {
q *qstash.Client
continueURL string
roundTimeout time.Duration
}
func (p *runPublisher) publishContinue(runID string, delay time.Duration) (string, error) {
res, err := p.q.PublishJSON(qstash.PublishJSONOptions{
Url: p.continueURL,
Body: map[string]any{"run_id": runID},
Delay: upstashSeconds(delay),
Timeout: fmt.Sprintf("%ds", int((p.roundTimeout + publishSlack).Seconds())),
})
if err != nil {
return "", fmt.Errorf("publishing continue for run %s: %w", runID, err)
}
return res.MessageId, nil
}
The Timeout here is the Upstash timeout, that is, how much time QStash will wait for our endpoint to answer. publishSlack is the amount of slack we would want to add to our deadline if something goes wrong. So the total is the amount of time QStash would wait for our endpoint.
Verifying an incoming request from QStash :
func (s *server) verified(w http.ResponseWriter, r *http.Request) ([]byte, error) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBody))
if err != nil {
return nil, fmt.Errorf("reading body: %w", err)
}
err = s.queue.receiver.Verify(qstash.VerifyOptions{
Signature: r.Header.Get("Upstash-Signature"),
Body: string(body),
Url: s.queue.continueURL,
})
if err != nil {
return nil, fmt.Errorf("bad signature: %w", err)
}
return body, nil
}
Let us see how we write the handleContinue function.
We verify the signature, that it has come from a legitimate source (QStash) and verify if the run_id is correctly formatted. round runs a single round of the loop under the lock.
func (s *server) handleContinue(w http.ResponseWriter, r *http.Request) {
body, err := s.verified(w, r)
if err != nil {
slog.Warn("rejected a continue", "err", err)
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "bad signature"})
return
}
var msg struct {
RunID string `json:"run_id"`
}
// unmarshal the body, and reject a run_id that does not match runIDPattern
log := slog.With("req", reqID, "run", msg.RunID,
"retried", r.Header.Get("Upstash-Retried"))
log.Info("continue received")
ctx, cancel := context.WithTimeout(r.Context(), s.timeout)
defer cancel()
answer, err := s.round(ctx, log, msg.RunID, noTicket)
// ...
}
func noTicket() (string, error) {
return "", errors.New("run has no recorded ticket: it was never created through POST /tickets")
}
We return a 409 if the same run is already in flight. It is not a 2XX, so QStash delivers the same message again. If the deadline exceeds, we just re-publish the run on the queue, and return a 200. It is the same as triggering the first run and returning immediately after publishing the message. Any other error is returned normally as a 500 and QStash retries it 3 times. It has its own backoff. After 3 times, it gets put into the dead letter queue of QStash. And if we want, we can replay it later manually. Otherwise the run is successful.
switch {
case errors.Is(err, errRunLocked):
w.Header().Set("Retry-After", retryAfter(s.lockTTL))
log.Warn("refused, the run is already in flight")
writeJSON(w, http.StatusConflict, map[string]string{"error": "this run is already being worked on"})
case errors.Is(err, context.DeadlineExceeded):
messageID, perr := s.queue.pub.publishContinue(msg.RunID, 0)
if perr != nil {
log.Error("round ended but the next one could not be published", "err", perr)
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "could not continue the run"})
return
}
log.Info("round ended, continuing", "msg", messageID)
writeJSON(w, http.StatusOK, map[string]string{"status": "continuing"})
case err != nil:
log.Error("round failed", "err", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
default:
log.Info("run done")
writeJSON(w, http.StatusOK, map[string]string{"status": "done", "answer": answer})
}
The Retry-After on that 409 should not be a constant, otherwise every retry can land while a crashed run still holds the lock, and the run is put in the DLQ without it actually failing.
func retryAfter(lockTTL time.Duration) string {
seconds := int(math.Ceil(lockTTL.Seconds() / 2))
if seconds < 1 {
seconds = 1
}
return strconv.Itoa(seconds)
}
Then we have the round function, where we grab the lock for the round of a run, and run a step for the ticket. Yes! a ticket is like any other step now.
func (s *server) round(
ctx context.Context, log *slog.Logger,
runID string, ticket func() (string, error),
) (string, error) {
token := rand.Text()
locked, err := s.store.TryLock(ctx, runID, token, s.lockTTL)
if err != nil {
return "", fmt.Errorf("taking the run lock: %w", err)
}
if !locked {
return "", errRunLocked
}
// the lock is released in a defer, exactly as in handleTicket above
engine := justonce.New(runID, s.store)
message, err := justonce.Step(ctx, engine, "ticket", ticket)
if err != nil {
return "", err
}
start := time.Now()
answer, err := s.agent.Run(ctx, engine, message)
replayed, ran := engine.Stats()
log.Info("round finished", "took", time.Since(start), "replayed", replayed, "ran", ran)
return answer, err
}
Now we do not need to retry. The agent does it for us. We just need the client to post a ticket.
POST /tickets → {"req":"CUWJQCIT","run":"run_q4_1","status":"accepted"} HTTP 202 in 0.11s
Notice how the replayed and ran counters are beautifully showing how our system is behaving. Our code publishes when the deadline is hit, and QStash delivers whatever is published on the queue. It's beautiful, isn't it?
14:30:16.873 ticket accepted run=run_q4_1 msg=msg_SsSaiS4nUd1vhM...
14:30:17.242 continue received req=645HBOGE retried=0
14:30:19.743 round finished took=2.448s replayed=1 ran=4
14:30:19.772 round ended, continuing
14:30:20.750 continue received req=AHWXSDLF retried=0
14:30:23.251 round finished took=2.447s replayed=5 ran=4
14:30:23.282 round ended, continuing
14:30:24.260 continue received req=FPVSKNN5 retried=0
14:30:25.619 email sent to_domain=example.com step=run_q4_1:tool-5-0
14:30:26.703 round finished took=2.389s replayed=9 ran=3
14:30:26.730 run done
Can you see replayed is equal to one? That's our actual ticket, the first one which the client sent. It is actually recorded by the POST /tickets endpoint, and it is replayed by the first round.
We also have a UI that you can play with (details in ReadMe) :
Running it against a real LLM
I hit a few very interesting bugs. The first was that I used a real LLM and I told it that I have placed these 5 orders and I have been charged extra.
Now there were two duplicate charges for one order, making it 3 charges for one order, and 1 duplicate charge for another order, making it 2 charges for another. Now the ledger doesn't differentiate it very nicely. It has incremental IDs, and nothing in it says which charge is the original. So for the order with 1 duplicate I was refunded correctly, that is 1 time, and for the order with 3 charges I was given the refund 3 times.
The thing which is wrong is that there is no rule at all. The model doesn't know what is an original charge and what is a duplicate charge, and the provider, which is a mock, doesn't know how to not refund everything.
We make the change in the tool. It cannot refund everything. As it can read the orders database and the ledger, it calculates the surplus and it refuses anything beyond it. So there are two fixes: enforcing the conditional inside the tool, and making the prompt better (you can check the repository for the better prompt). The agent can only refund the surplus, and above the approval threshold it needs a human approval (see later sections).
The extra refund error can be handled by enforcing not spending more than the surplus in issue_refund tool :
out, allowed, err := p.refuseBeyondSurplus(
ctx, orders, a.OrderID, a.ChargeID, "refund:"+key, a.AmountPaise)
if err != nil {
return "", err
}
if !allowed {
return out, nil
}
refuseBeyondSurplus is a very crucial function and it works like this :
The first thing which this function does is it retrieves the charge and refund entries from the ledger, and it calculates the surplus amount that can be refunded, using this formula:
surplus = charged − what the order is worth − already refunded
The actual worth of the order comes from the orders database, and every charge related to this order is calculated from the ledger.
func (p *ProviderClient) refuseBeyondSurplus(
ctx context.Context, orders *sql.DB,
orderID, chargeID, idempotencyKey string, want int64,
) (string, bool, error) {
var owed int64
err := orders.QueryRowContext(ctx,
`SELECT amount_paise FROM orders WHERE id = ?`, orderID).Scan(&owed)
// sql.ErrNoRows is a refusal: no such order, so nothing about it is
// refundable. any other error is returned as an error.
entries, err := p.ledgerFor(ctx, orderID)
if err != nil {
return "", false, err
}
var charged, refunded int64
var chargeFound bool
for _, e := range entries {
switch e.Kind {
case "charge":
charged += e.AmountPaise
if e.ID == chargeID {
chargeFound = true
}
case "refund":
refunded += e.AmountPaise
}
}
// a charge that is not on this order is a refusal too
// ...
}
And it is very important that we differentiate another refund from a retry of our refund. And for that we use the idempotency key. So a refund which carries this step's key is our own earlier attempt, otherwise it's just a new refund request. Now refunds show an idempotency key, because we need to differentiate a refund retry from a fresh refund.
{"id":"rf_1","kind":"refund","order_id":"4512","charge_id":"ch_2","amount_paise":150000,"idempotency_key":"refund:r5:tool-4-0"}
for _, e := range entries {
if e.Kind == "refund" && e.IdempotencyKey == idempotencyKey {
return "", true, nil
}
}
And if the required amount is more than the surplus amount, then we reject the request.
if surplus := charged - owed - refunded; want > surplus {
out, rerr := refusal(
"order %s was charged %d paise and is worth %d, and %d has already been refunded, "+
"so only %d paise of surplus is refundable and %d was asked for",
orderID, charged, owed, refunded, max(surplus, 0), want)
return out, false, rerr
}
And if the total amount which is refunded plus the required amount is more than what an agent can approve, then as well we reject it with a refusal. The total amount here is whatever the order's total is, and not one request.
if total := refunded + want; total > ApprovalThreshold {
out, rerr := refusal(
"refunding %d paise would take the total refunded on order %s to %d, "+
"above the %d paise that can be refunded without human approval, "+
"so this refund needs a human and cannot be issued here",
want, orderID, total, ApprovalThreshold)
return out, false, rerr
}
return "", true, nil
}
Now the second refusal will be read differently by the agent, and the customer will be emailed about the human intervention.
The second bug, which I hate, was that I was rate limited by the LLM. Here, the fix would be to handle this and republish it using QStash with a delay and return a 2xx. We recognize this error as a typed error from the llm-client. Let us fix the rate limit bug :
In the handleContinue function, we include a case for the Rate Limit Error, retry after some time and return with a 2xx code.
case errors.Is(err, llm.ErrRateLimited):
wait := rateLimitWait // 30s if the provider didn't say
var limited *llm.RateLimitError
if errors.As(err, &limited) && limited.RetryAfter > 0 {
wait = limited.RetryAfter
}
messageID, perr := s.queue.pub.publishContinue(msg.RunID, wait)
// ...
writeJSON(w, http.StatusOK, map[string]string{"status": "rate limited, continuing"})
Now, how does QStash handle human intervention? We will see that in the next section.
Pausing the run for a person
We add a new method in the Redis Store, i.e SetOnce. It checks if the key is already set, and if it is not, we set it.
func (s *RedisStore) SetOnce(ctx context.Context, runID, step string, value json.RawMessage) (bool, error) {
created, err := setOnce.Run(ctx, s.rdb,
[]string{stepKey(runID, step)},
[]byte(value), s.ttl.Milliseconds(),
).Int()
if err != nil {
return false, fmt.Errorf("redis setonce %s: %w", stepKey(runID, step), err)
}
return created == 1, nil
}
This SetOnce actually decides who wins the race. Say if the human doesn't approve in the set deadline, the timer can wake the run first, and write that the decision is rejected. And if the human approves, this SetOnce gets active, and the decision is approved, and it also can be rejected if the human rejects it. And it cannot be set twice, so this key can only be fired once. This is also a guarantee against the case where QStash can make things worse by delivering the timer message twice. So if the first timer has already set the key, the second timer cannot set it.
Now, when does the agent say that human approval is required? We can decide to pause the loop at two places.
The first is the tool itself. A request_approval tool is added, which is called by the model when it reads a refusal, and we put WaitForEvent in that tool.
The second is the agent loop. Before wrapping anything in the step, the agent decides: would this need an approval? And then we can wait for the event.
We pick the second one. With the first, we would be depending too much on the model. And the engine's handle, the Ctx, has a claim function which will automatically reject if this step comes up twice, because it only keeps unique steps. So in the agent loop, the approval gets its own name, like approval-tool-4-0, and it would be deterministic, and would not depend on the model at all.
Tool takes a new field which is NeedsApproval closure.
type Tool struct {
//...
NeedsApproval func(ctx context.Context, args json.RawMessage) (needed bool, why string, err error)
}
justonce has a WaitForEvent function :
If the decision is already there in the store, someone has already made it, either the timer or the person. If there is nothing there, then a pending tag is written against that run and event, and it returns a suspended error.
func WaitForEvent(ctx context.Context, c *Ctx, event, why string) (json.RawMessage, error) {
if event == "" {
return nil, fmt.Errorf("justonce: run %s waited on an event with no name", c.RunID)
}
raw, ok, err := c.store.Get(ctx, c.RunID, EventName(event))
if err != nil {
return nil, fmt.Errorf("justonce: run %s event %s: %w", c.RunID, event, err)
}
if ok {
c.count(true)
return raw, nil
}
if _, err := markPending(ctx, c, event, why); err != nil {
return nil, err
}
return nil, &SuspendedError{Event: event, Why: why}
}
And then we check if the approval is required in the agent loop :
needed, why, err := tl.NeedsApproval(stepCtx, json.RawMessage(c.Function.Arguments))
if err != nil {
return "", err
}
if !needed {
return a.call(stepCtx, c)
}
// the event is named after the step, so it is as deterministic as the step
// is. Two refunds in one run are two steps and therefore two decisions,
// and a person approving one has not approved the other.
decision, err := justonce.WaitForEvent(ctx, engine, "approval-"+step, why)
if err != nil {
// ErrSuspended included: nothing is recorded, the round ends, and the
// run waits exactly here until somebody decides.
return "", err
}
If the agent decides the approval is required, the suspend error propagates up and the lock for the run is released. Then this waits on a human, and either a human or the timer fires.
The timeout and the human do the same thing, but the timeout endpoint is called by QStash and the person calls the endpoint manually. And both write different things.
func (p *runPublisher) publishTimeout(runID, event string, after time.Duration) (string, error) {
res, err := p.q.PublishJSON(qstash.PublishJSONOptions{
Url: p.timeoutURL,
Body: map[string]any{"run_id": runID, "event": event},
Delay: upstashSeconds(after),
Timeout: upstashSeconds(p.roundTimeout + publishSlack),
})
if err != nil {
return "", fmt.Errorf("publishing the timeout for %s of run %s: %w", event, runID, err)
}
return res.MessageId, nil
}
If the timer expires or a human hits the endpoint, our code just publishes it to QStash's queue, and QStash delivers the message :
messageID, err := s.queue.pub.publishContinue(runID, 0)
Two bugs in the approval path
When I was running the demo for this, I hit a bug, and this was an interesting one. So after getting a refund approved by a human, I hit the gate which was enforced in the issue_refund tool, and it rejected the refund. So I needed to make sure that if it is approved once by a human, the tool doesn't reject it for the same clause. And the fix is this code snippet.
type approvalCtx struct{}
func WithApproval(ctx context.Context, by string) context.Context {
return context.WithValue(ctx, approvalCtx{}, by)
}
func ApprovalFrom(ctx context.Context) (string, bool) {
by, ok := ctx.Value(approvalCtx{}).(string)
return by, ok
}
The agent, once the decision comes back approved:
return a.call(tools.WithApproval(stepCtx, d.By), c)
And the tool, in refuseBeyondSurplus:
if _, approved := ApprovalFrom(ctx); approved {
return "", true, nil
}
if total := refunded + want; total > ApprovalThreshold {
// ... the refusal ...
}
So the fix is that I just inject whether it is approved or not, in a context. And I check from the context if it is already approved, and this check has to be after the surplus rule, and before the threshold rule. Because even if it is a human, they cannot approve the refund if it is more than the surplus. But if the human has approved, then the approval clause can be ignored. So that's why it sits in the middle.
I also observed that sometimes the model issues a partial refund for a request that was rejected by a human. And that should not happen. So using the SetOnce method that I wrote, I lock this so that the agent cannot touch it again without a human approval.
The decision is remembered against the order, not against the request that was refused:
func RefundScope(orderID string) string { return "order:" + orderID }
func Refuse(ctx context.Context, c *Ctx, scope string) error {
events, ok := c.store.(EventStore)
if !ok {
return fmt.Errorf("justonce: this store cannot record a refusal for run %s", c.RunID)
}
if _, err := events.SetOnce(ctx, c.RunID, refusedPrefix+scope, json.RawMessage(`{"refused":true}`)); err != nil {
return fmt.Errorf("justonce: refusing %s in run %s: %w", scope, c.RunID, err)
}
return nil
}
func Refused(ctx context.Context, c *Ctx, scope string) (bool, error) {
_, found, err := c.store.Get(ctx, c.RunID, refusedPrefix+scope)
if err != nil {
return false, fmt.Errorf("justonce: reading the refusals of run %s: %w", c.RunID, err)
}
return found, nil
}
It is written the moment the rejection comes back, before the model is told:
if d.Decision != "approved" {
if ap.Scope != "" {
if err := justonce.Refuse(ctx, engine, ap.Scope); err != nil {
return "", err
}
}
return refused(d, why)
}
And read before the next call on the same order:
if ap.Scope != "" && !ap.Needed {
refused, err := justonce.Refused(ctx, engine, ap.Scope)
if err != nil {
return "", err
}
if refused {
ap.Needed = true
ap.Why = "a person has already refused a refund on " + ap.Scope +
", so anything further on it needs a person too"
}
}
Upstash Workflow is nice
Yeah, I think we have built something like Upstash Workflow. But when I say that, it's with a pinch of salt, because the differences can be huge in places.
Their context.run is similar to our Step. Our run ID is supplied by the client, whereas they have their own maintained workflow run ID. They have a managed storage, and we have our own little Redis storage. The concept of run lock is used by them as well, and they call it a singleton workflow.
They have waitForEvent and notify for doing stuff like the human intervention which we did. They also have a timeout option like we had.
Our DLQ is manual, that is we have to replay the events manually, but theirs gives us restart and resume from the failed step. What we do not have is flow control, which they give us out of the box. They allow us to control the rate and the period per key. And they also give us child workflows, and we can invoke many served workflows. There are many more things that you can check out in the documentation.
Even with QStash, we could have made QStash call the LLM API on our behalf, but I thought it was not that necessary for the demo. Although we can write it, I have skipped it in this blog. Upstash Workflow's context.call allows us to do this exact same thing. There is one more very good thing about context.call: it can wait up to 12 hours, and doing this, it consumes no compute. And I like this thing about them very much.
On the other hand, Upstash Workflow does not provide us with a Go SDK. But QStash does, and that's why I chose to build it using QStash. That's not the primary reason, but one of the reasons. The other reason is obviously that I like to go into rabbit holes and see how a durable execution engine for an agent works.
So for building something like this, you can use Upstash Workflow out of the box. Or you can take the long route and start designing a nice little system like we just did.
Conclusion
I swear this was a very fun build. And I really enjoyed using QStash. Throughout this post, we discovered how determinism makes our life easy, and how a simple job queue makes our agent run flawlessly. I also like the idea of the push-based work queue by QStash, and it is really nice to work with. Upstash Redis gives us a cloud-hosted Redis instance out of the box. And honestly, I really like Redis.
So folks, whenever you have to design a system, you just need to think what can go wrong, and the fix is right there in front of you.
That is it for this post. Hope you enjoyed it. See you in the next one.












Top comments (0)