AWS Builder Center

Lambda Durable Functions for a Governed Three-Level Order-Book Workflow

Lambda Durable Functions for a Governed Three-Level Order-Book Workflow

Series: Financial Service (19 articles)

  1. …
  2. 5
    Lambda Durable Functions for a Governed Three-Level Order-Book Workflow This article
Dev @ Vertex Macro

Lambda Durable Functions for a Governed Three-Level Order-Book Workflow

An enterprise architecture paper for financial-services builders

Financial markets are unforgiving teachers. A system may be elegant in a design review and still fail the moment a venue sends duplicate messages, an approval arrives hours late, an upstream gateway times out after accepting an order, or a deployment changes code while an execution is paused. The real standard is not whether software follows the happy path. The standard is whether the institution can explain, reproduce, control, and recover every consequential transition without losing customer trust.
AWS Lambda Durable Functions changes an important part of that engineering equation. It allows a team to express a multi-step application workflow as sequential code inside a Lambda function while AWS manages durable checkpoints, suspension, resumption, retries, and replay. A durable execution may remain active for as long as one year. A durable wait stops the active invocation, so on-demand compute duration is not charged while the workflow is suspended. When execution resumes after a wait or interruption, the handler runs again from the beginning, but the Durable Execution SDK returns persisted results for completed durable operations and rapidly advances the program to the unfinished work.
That is not merely a longer Lambda timeout. The familiar 15-minute limit still applies to an individual invocation. Durability is created by a managed lifecycle spanning multiple sub-invocations, using checkpoints as the permanent memory of completed operations. This distinction matters because it defines both the value and the discipline of the model. Durable Functions can simplify application orchestration, but they do not remove the need for deterministic code, idempotent side effects, market-data sequence control, explicit risk limits, or independent books and records.
For a financial institution that wants to use AI-assisted coding and begin with a three-level order-book application, the opportunity is compelling. The team can keep the business narrative in one readable program rather than distributing it across a state-machine definition and many small orchestration functions. The trade-off is equally clear. A single deployable function must not become a single uncontrolled blast radius. The right design is a cohesive application unit with strict internal boundaries, durable steps, small checkpoint payloads, external systems of record, immutable evidence, and an explicit path to decompose when throughput, latency, ownership, or regulatory boundaries demand it.

The customer problem is not orchestration; it is controlled certainty

A three-level order book represents the best three bid prices and best three ask prices, together with aggregate quantity at each level. Bids are ordered from highest to lowest because the buyer offering the most aggressive price has priority. Asks are ordered from lowest to highest because the seller accepting the lowest price is most aggressive. The highest bid and lowest ask form the inside market. Their difference is the bid-ask spread, which is one visible measure of liquidity and immediate transaction cost. Market depth extends the view beyond the inside quote by showing the quantity available across several price levels.
Limit orders add displayed or hidden liquidity when they rest rather than execute immediately. Market orders consume available liquidity at the best accessible prices. Iceberg orders expose only part of a larger parent quantity and replenish displayed size according to venue rules. Price-time priority usually gives precedence to the better price and then to the earliest order at that price, although allocation rules vary by market. Direct market access shortens the route between an institutional strategy and an exchange, increasing the value of speed while also increasing the importance of pre-trade controls. VWAP and TWAP algorithms divide a parent order over volume or time, but their actual execution quality depends on spread, available depth, queue position, volatility, information leakage, fees, and market impact.
Modern electronic markets make even a three-level view deceptive if it is treated as complete truth. High-frequency participants can add and cancel liquidity faster than a human can perceive. Displayed quantity may disappear before an order reaches the venue. Dark liquidity is absent from a displayed book. Spoofing creates a false impression of supply or demand when orders are placed without bona fide intent to execute. An order-flow imbalance can contain short-horizon information, but it is not a guaranteed directional signal. A depth chart is therefore an observation, not a promise.
The business problem is to turn this changing observation into a controlled decision process. The application must validate source sequence, reject stale or crossed snapshots unless the venue semantics justify them, calculate spread and imbalance consistently, apply customer and instrument limits, generate an execution recommendation, obtain approval where policy requires it, submit an order exactly once from the institution's point of view, reconcile an uncertain outcome, and retain evidence that lets operations, risk, compliance, audit, and engineering reconstruct the decision.
In traditional serverless designs, this often becomes a collection of Lambda functions, queues, database status fields, retry schedulers, callback handlers, and a separate AWS Step Functions state machine. That architecture remains excellent when the workflow crosses many teams, needs strong visual orchestration, or benefits from service-native integrations. It can nevertheless create cognitive distance for a small application team. AI coding tools must navigate infrastructure definitions, payload contracts, deployment units, and retry behavior spread across repositories. The cost is not only infrastructure. It is the number of places in which meaning can diverge.
Durable Functions offers a different starting point. The application can read like the business: ingest a snapshot, validate it, calculate the three levels, evaluate risk, preserve deterministic decision inputs, request approval when necessary, submit through an idempotency boundary, confirm status, record the final evidence, and close. The source code becomes an executable operating procedure.

The checkpoint-and-replay model

The central primitive is context.step(). A step encloses business logic whose result must be durable. When the step completes, its result is checkpointed. During replay, the SDK supplies that checkpointed result rather than running the step again. A step may apply a configurable retry strategy with backoff. External API calls, database mutations, LLM requests, current timestamps, random identifiers, and any operation with a side effect or non-deterministic result belong inside a durable step.
The central suspension primitive is context.wait(). It records a durable timer and terminates the current invocation. The workflow consumes no on-demand Lambda compute duration while it waits. At the scheduled time, Lambda starts another sub-invocation. The handler replays from the beginning, completed operations are skipped through their checkpointed results, and processing continues after the wait.
context.waitForCallback() creates a durable handoff to an external actor. It can send a callback identifier to an approval service, operations portal, email workflow, or another system and then suspend until that actor calls the Lambda durable callback API. A timeout is essential. An approval must never own an open resource forever merely because someone left the firm, a mailbox rule changed, or a downstream system lost the request.
context.waitForCondition() supports controlled polling. Its check function runs as a durable step, state is checkpointed between attempts, and the function suspends during backoff periods. This is valuable when a broker or venue adapter exposes order status through polling but does not support a trustworthy callback. A callback remains preferable when the external system can notify completion because it reduces polling traffic and state transitions.
Replay imposes a non-negotiable determinism contract. Calling crypto.randomUUID() or Date.now() directly in the replayed path can produce a different value each time and break the relationship between code and history. Reading a mutable configuration file, iterating over an unordered collection, or branching on a live API response outside a step creates the same class of defect. Non-deterministic values must be created in a named step and returned as checkpointed data. Large data should not be returned from the step. It should be stored in Amazon S3 or an appropriate database, with the checkpoint carrying a compact immutable reference, hash, version, and business identifier.
Checkpointing also does not magically turn every side effect into exactly-once execution. A process can call a broker successfully and fail before the successful result is checkpointed. The replay may then attempt the call again. The correct design is business idempotency. The institution generates a stable client order identifier before submission, stores an intent record with a conditional write, passes the same identifier on every attempt, and reconciles any ambiguous response by querying the broker or venue. The useful guarantee is not the phrase exactly once. The useful guarantee is that duplicate technical attempts converge on one business outcome.

Why a single function can raise the bar, and when it cannot

A single durable function can reduce cognitive load for a team that uses AI coding extensively. The complete workflow is visible in one module. An AI assistant can reason about data contracts and error paths with less cross-file ambiguity. Local tests can replay operation histories. Pull requests can show how a risk decision, wait, callback, and compensation path fit together. The team can ship a thin vertical slice without first designing a distributed orchestration estate.
This simplification aligns with Customer Obsession because it shortens the distance from a customer need to a reliable outcome. It aligns with Invent and Simplify because it removes undifferentiated coordination code. It reflects Bias for Action when the first release is reversible, scoped, observed, and protected by controls. It reflects Ownership and Insist on the Highest Standards only when the team also accepts responsibility for replay safety, evidence retention, incident response, capacity, cost, and change governance.
The phrase one Lambda function must not be misunderstood as one giant unstructured block. The deployment unit may be one function, while the code contains domain modules for market-data normalization, book construction, pre-trade risk, execution policy, broker access, audit evidence, and notification. Each durable step has a stable name and a narrow contract. Pure calculations remain pure functions. External effects pass through adapters. The handler coordinates; it does not conceal business logic.
There are boundaries that this pattern should not cross. Lambda Durable Functions is not an exchange matching engine, a co-located low-latency gateway, or the in-memory canonical order book for sub-millisecond trading. Cold starts, managed-network variance, checkpoint operations, replay, and regional service dependencies are incompatible with deterministic microsecond latency. The pattern is appropriate for application-layer workflows such as low-frequency strategy initiation, order staging, risk approval, exception handling, AI-assisted trade review, client-order lifecycle coordination, and processing a compact three-level snapshot. The market-data feed handler and high-performance matching path should remain on infrastructure designed for their latency and availability objectives.
A durable function also does not replace AWS Step Functions in every case. Step Functions remains compelling when orchestration spans many independently owned services, when operations teams benefit from an explicit visual state machine, when the workflow is primarily service integration rather than application code, or when organizational separation is itself a control. Durable Functions is strongest when sequential code is the most natural representation of one team's application logic.

A reference architecture for a three-level order-book workflow

The external boundary accepts a normalized market-data snapshot or a trading instruction through Amazon API Gateway, an Amazon Kinesis Data Stream consumer, or Amazon SQS. The upstream transport depends on rate, ordering requirements, and producer behavior. The event contains a venue, instrument, source sequence number, source timestamp, bid and ask updates, customer or strategy identity, correlation identifier, and schema version. It does not contain credentials or unrestricted free-form instructions.
The durable function begins by creating or retrieving a stable execution identity. It normalizes decimal prices and quantities without binary floating-point error. It validates that levels are positive, the sequence number is newer than the last committed source sequence, and the book is not crossed unless the market's auction or venue state permits it. It then sorts and aggregates the best three bid and ask levels. The resulting snapshot is written to an external system of record such as Amazon DynamoDB for current state and Amazon S3 with S3 Object Lock where immutable retention is required. The checkpoint stores the object URI, content hash, source sequence, and calculation version rather than every market-data row.
The decision step calculates the spread, mid-price, cumulative depth, and order-flow imbalance. A simple imbalance measure over three levels is the difference between cumulative bid and ask quantity divided by their sum. The calculation must explicitly handle an empty side and must be versioned. It may inform an execution policy, but it must not bypass risk controls. The institution records which model or rule version generated a recommendation and keeps the features used at decision time.
The risk step checks price collars, maximum order quantity, maximum notional, position limits, credit availability, restricted instruments, venue status, stale-data thresholds, duplicate intent, trading-session state, and any required kill switch. Critical controls should use strongly consistent reads or conditional writes where the data store supports them. A permissive default is unacceptable. If required risk data cannot be obtained, the workflow should fail closed, preserve evidence, and route the case to operations.
A low-risk instruction that remains within policy can continue automatically. A large, unusual, illiquid, or AI-influenced instruction can enter waitForCallback(). The approval request includes a compact summary, immutable evidence pointers, expiry, reason codes, and callback identifier. The approver sees current market context but approves a specific intent version. If the market moves beyond an allowed threshold before approval arrives, the earlier approval does not silently authorize a materially different trade. The function revalidates both market conditions and risk immediately before submission.
The submission step writes an order-intent record using a conditional expression, then sends the stable client order identifier to the broker or venue adapter. If the network returns an uncertain result, the function does not create a fresh identifier. It uses waitForCondition() to reconcile the existing client order identifier until the external system reports accepted, rejected, filled, cancelled, or expired. The finalization step writes the terminal outcome, execution evidence, actual fills, fees, timestamps, and the relationship between parent and child orders. An immutable audit copy is retained according to the institution's policy.
CloudWatch records operational telemetry, but logs are not the sole book of record. Logs should use structured fields and avoid full customer data, secret material, or excessive checkpoint payloads. AWS X-Ray or supported tracing provides request linkage where appropriate. Amazon CloudWatch alarms monitor failed durable executions, timed-out executions, running-execution utilization, operation count, checkpoint bytes, throttles, callback age, risk rejection anomalies, and reconciliation backlog. AWS CloudTrail records control-plane and callback API activity. AWS KMS customer-managed keys can protect durable execution data where policy requires them.

An illustrative TypeScript durable workflow

The following code is intentionally compact. It shows the shape of the workflow, not a production trading system. Production code requires venue-specific semantics, decimal libraries, schema validation, authentication, authorization, idempotent adapters, independent risk review, testing, monitoring, and legal or regulatory approval.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import {
DurableContext,
withDurableExecution,
} from "@aws/durable-execution-sdk-js";
import { randomUUID } from "node:crypto";

type Level = { price: string; quantity: string };
type TradingEvent = {
venue: string;
instrument: string;
sequence: number;
sourceTimestamp: string;
bids: Level[];
asks: Level[];
requestedSide: "BUY" | "SELL";
requestedQuantity: string;
limitPrice?: string;
strategyId: string;
};

export const handler = withDurableExecution(
async (event: TradingEvent, context: DurableContext) => {
const identity = await context.step("create-execution-identity", async () => ({
clientOrderId: randomUUID(),
decisionTimestamp: new Date().toISOString(),
}));

const snapshot = await context.step("validate-and-store-book", async () => {
const topThree = buildValidatedTopThree(event);
const evidence = await storeImmutableSnapshot(topThree, event);
return {
venue: event.venue,
instrument: event.instrument,
sequence: event.sequence,
sourceTimestamp: event.sourceTimestamp,
topThree,
evidenceUri: evidence.uri,
sha256: evidence.sha256,
};
});

const decision = await context.step("calculate-decision", async () => {
return calculateSpreadDepthAndImbalance(snapshot, event);
});

const initialRisk = await context.step("initial-pre-trade-risk", async () => {
return evaluateRisk({ event, snapshot, decision, identity });
});

if (initialRisk.decision === "REJECT") {
return context.step("record-risk-rejection", async () =>
recordTerminalOutcome(identity.clientOrderId, initialRisk)
);
}

if (initialRisk.decision === "REQUIRE_APPROVAL") {
const approval = await context.waitForCallback(
"wait-for-trade-approval",
async (callbackId) => {
await sendApprovalRequest({
callbackId,
clientOrderId: identity.clientOrderId,
evidenceUri: snapshot.evidenceUri,
riskReasons: initialRisk.reasons,
expiresAt: initialRisk.approvalExpiresAt,
});
},
{ timeout: { hours: 4 } },
);

await context.step("record-approval", async () =>
persistApproval(identity.clientOrderId, approval)
);
}

const finalRisk = await context.step("final-pre-submit-risk", async () => {
return revalidateImmediatelyBeforeSubmission({
event,
snapshot,
decision,
identity,
});
});

if (finalRisk.decision !== "ALLOW") {
return context.step("record-final-risk-stop", async () =>
recordTerminalOutcome(identity.clientOrderId, finalRisk)
);
}

await context.step("create-idempotent-order-intent", async () => {
return createOrderIntentConditionally({
clientOrderId: identity.clientOrderId,
event,
snapshot,
decision,
finalRisk,
});
});

await context.step("submit-order", async () => {
return submitUsingStableClientOrderId({
clientOrderId: identity.clientOrderId,
event,
});
});

const terminalStatus = await context.waitForCondition(
"reconcile-order-status",
async (state: { clientOrderId: string; status: string; done: boolean }) => {
const status = await getOrderStatus(state.clientOrderId);
return {
clientOrderId: state.clientOrderId,
status: status.code,
done: ["FILLED", "CANCELLED", "REJECTED", "EXPIRED"].includes(status.code),
};
},
{
initialState: {
clientOrderId: identity.clientOrderId,
status: "PENDING",
done: false,
},
waitStrategy: (state, attempt) => ({
shouldContinue: !state.done && attempt < 120,
delay: { seconds: Math.min(2 ** attempt, 60) },
}),
},
);

return context.step("finalize-audit-evidence", async () => {
return finalizeOrderEvidence({
identity,
event,
snapshot,
decision,
finalRisk,
terminalStatus,
});
});
},
);
The most important line is not a particular API call. It is the boundary around non-determinism. The UUID and current timestamp are created in a step, so replay returns their persisted values. The external snapshot write, approval notification, intent creation, broker submission, status lookup, and final record are durable operations. Their adapters must still be idempotent. The pure arithmetic in buildValidatedTopThree and calculateSpreadDepthAndImbalance should be deterministic, versioned, and covered by property-based tests.

Setting up the solution in the AWS Management Console

Sign in to the AWS Management Console with a role authorized to create Lambda functions and execution roles. Select the target AWS Region only after checking current regional availability for Durable Functions and validating the institution's data-residency, latency, and resilience requirements. Open AWS Lambda, choose Functions, choose Create function, and choose Author from scratch. Enter a lowercase operational name such as fsi-three-level-order-workflow. Select a currently supported durable runtime, such as Node.js 24 or Python 3.14 where available. Select Enable durable execution during creation. Durable execution must be enabled when the function is created; it cannot be added later to an existing function.
Create a dedicated execution role rather than sharing a broad application role. The console can add the basic durable permissions required for checkpointing and retrieving execution state. Extend that role only with access to the exact DynamoDB tables, S3 prefixes, KMS keys, Secrets Manager secrets, CloudWatch resources, and outbound interfaces needed by this function. Scope durable permissions to qualified function resources. Separate the human or service role that invokes the function from the execution role used by the function. Separate callback-sender permissions again, because an actor able to complete an approval callback controls a material state transition.
In the function's durable configuration, set an execution timeout based on the business lifecycle, not the maximum merely because it exists. The valid technical range can extend to 31,622,400 seconds, approximately one year. Set history retention according to operational debugging and audit needs. Lambda's post-completion durable history retention is configurable from 1 to 90 days and defaults to 14 days, but that service history is not a substitute for the institution's regulated records archive. Configure a customer-managed AWS KMS key if required. Keep checkpoint state small because storage written and retention are billable and because large state makes operations harder to inspect.
Package the Durable Execution SDK with the production deployment even when a supported runtime includes it, so the application controls and tests the SDK version. Use the console editor only for a first controlled experiment. Move production code to a version-controlled pipeline using AWS CloudFormation, AWS SAM, AWS CDK, or another approved infrastructure-as-code system. Durable production deployments require published versions or aliases for qualified invocation. Never allow a year-long workflow to drift silently across incompatible code. Establish a deployment policy that preserves old versions until their durable executions complete or are deliberately migrated or stopped.
Create DynamoDB tables for the current order intent, source sequence guard, and order status if the application needs low-latency conditional state. Use a composite key that reflects the business uniqueness boundary, such as venue plus client order identifier or account plus intent identifier. Use conditional writes to prevent duplicate intent creation and stale sequence commits. Enable point-in-time recovery where required. Create an S3 evidence bucket with versioning, encryption, blocked public access, restrictive bucket policies, lifecycle rules, and S3 Object Lock when immutable retention is a policy requirement. Store bulky snapshots and reports in S3; store compact references and hashes in durable checkpoints.
Store broker credentials or API keys in AWS Secrets Manager, encrypt them with an approved KMS key, and grant read access only to the function role. If the broker endpoint requires private connectivity, configure VPC networking, route tables, security groups, network controls, and resilient egress. VPC attachment can affect latency and adds dependencies, so measure it. Use TLS, certificate validation, request signing where supported, and an allow-listed destination strategy. Do not embed secrets in code, environment variables containing plaintext, callback payloads, or checkpoints.
Add the TypeScript code and adapters, then publish a version and create an alias such as prod. Configure the approved ingress to invoke the alias rather than an unqualified mutable function. If using API Gateway, apply authentication, authorization, schema validation, throttling, AWS WAF where appropriate, and a request-size limit. If using Kinesis or SQS, configure failure handling, visibility or retry behavior, concurrency, and a dead-letter or failure destination consistent with the event source. Preserve ordering by instrument or partition key where the business logic requires it.
Open the Lambda Monitoring view and create CloudWatch alarms for durable execution failures, timeouts, stopped executions, running-execution quota utilization, excessive durable operation counts, excessive storage written, throttling, invocation errors, and abnormal duration. The service exposes durable metrics including cumulative operations and bytes written. Operational dashboards should also show approval age, source-sequence gaps, rejected snapshots, crossed books, final-risk stops, ambiguous submissions, reconciliation age, duplicate-intent attempts, broker error rates, and order terminal-state distribution.
Test with a synthetic instrument and a non-production broker simulator. Begin with deterministic fixtures for normal books, empty sides, duplicate levels, decimal edge cases, crossed books, stale timestamps, sequence gaps, duplicated events, callback timeout, delayed approval, broker acceptance followed by network failure, status polling failure, replay after an invocation timeout, and deployment while work is suspended. Inspect the durable execution history in the Lambda console and confirm that completed steps are skipped on replay. Confirm that the same client order identifier survives every replay. Confirm that a callback cannot approve the wrong intent, an expired approval cannot submit a trade, and a duplicate submission converges on one external order.
Promote through environments with separate accounts and roles. Use automated policy checks, dependency scanning, unit tests, replay tests, contract tests, failure injection, and a manual risk-control sign-off. Start with small notional and restricted instruments. Use reserved concurrency or upstream throttling to cap blast radius. Maintain a tested kill switch that stops new intent creation without destroying the ability to reconcile existing orders. A kill switch that only disables the function can be dangerous if it also prevents the institution from discovering whether already-submitted orders filled.

Cost, capacity, and the economics of waiting

Durable Functions retains normal Lambda request and active-duration charges, including sub-invocations created by replay, retry, and resume. Waits in on-demand functions do not incur compute-duration charges while suspended. Durable pricing adds charges for durable operations, data written by those operations, and retained data. The public pricing model has cited a flat rate of USD 8.00 per million durable operations; exact prices, free-tier treatment, data rates, and regional availability must be verified on the AWS Lambda pricing page when the workload is approved because cloud prices and regional terms can change.
A low operation price does not make careless polling free. A status check every second for hours creates operations, downstream traffic, logs, and pressure on broker APIs. Prefer callbacks when reliable external notification exists. Where polling is necessary, use exponential backoff with a cap and a business deadline. A three-level snapshot should remain compact. Checkpointing a full order-book history or LLM transcript on each transition creates avoidable storage and retention cost. Store large artifacts once, reference them by immutable URI and hash, and retain only what the control objective requires.
Capacity planning must include running durable execution quotas, maximum operations per execution, checkpoint-storage limits, upstream concurrency, DynamoDB capacity, broker rate limits, and callback volume. AWS documentation exposes metrics for operation count and cumulative storage written and describes service quotas such as a maximum operation count per execution. The production design should review current quotas in the chosen Region and obtain increases before go-live. A workflow that can remain open for months occupies logical capacity even when it consumes no compute duration.
The financial comparison should include engineering and control cost, not just cloud line items. Durable Functions can reduce state-management code, state-machine definitions, and operational fragmentation. Step Functions can reduce the cost of understanding cross-service control flow for teams that value its visual model and integrations. The least expensive architecture is the one that meets the control objective with the smallest long-term burden of defects, audit exceptions, and operational uncertainty.

Culture as a control plane

Technology will not rescue a trading team that punishes inconvenient truth. Google re:Work's account of Project Aristotle identified psychological safety, dependability, structure and clarity, meaning, and impact as important team dynamics, with psychological safety foundational to people speaking up. In financial systems, speaking up is not a soft benefit. It is an early-warning system. A developer must be able to say that a replay can duplicate an order. An operations analyst must be able to say that a dashboard hides stale approvals. A junior quant must be able to challenge an imbalance formula. A risk officer must be able to stop a launch without becoming an enemy of delivery.
Psychological safety does not mean lowering standards or avoiding accountability. It means making it safe to expose errors before the market exposes them. Dependability means owning remediation. Structure and clarity mean naming the decision owner, control owner, approver, incident commander, and rollback authority. Meaning and impact come from connecting engineering work to fair execution, customer protection, market integrity, and institutional resilience.
Amazon's Leadership Principles add the execution discipline. Customer Obsession requires the team to protect the customer's intended trade, not merely return a successful HTTP status. Ownership requires reconciliation after ambiguous submissions. Dive Deep requires comparing execution history, broker records, order intent, and logs rather than accepting the first plausible story. Are Right, A Lot requires seeking evidence that disproves the design. Have Backbone; Disagree and Commit allows engineers and risk officers to challenge weak idempotency or unsafe defaults before committing to the final decision. Bias for Action applies to reversible experiments with controlled notional, not irreversible exposure without guardrails. Insist on the Highest Standards means defects are fixed at the mechanism level so they stay fixed.
Bridgewater Associates' emphasis on radical truth and transparency contributes a useful operating idea, but it must be implemented with care. Evidence should be visible, assumptions should be explicit, and predictions should be compared with outcomes. Radical transparency without psychological safety can become public humiliation. Psychological safety without transparent evidence can become comfortable ambiguity. The synthesis is an idea meritocracy governed by respectful challenge: the execution history, sequence numbers, hashes, risk decisions, tests, and market outcomes carry more weight than title, confidence, or blame.
Adlerian thought adds social interest and separation of tasks. The engineer owns the quality of the code and evidence, but does not own another person's emotional reaction to bad news. The approver owns the approval decision. Risk owns the policy. Operations owns reconciliation according to the runbook. Leaders own the environment in which truth can travel upward. Separating tasks prevents rescuing, scapegoating, and hidden accountability while preserving cooperation around a shared institutional purpose.
Nonviolent Communication offers a precise language for incidents. The team distinguishes observation from judgment, names the operational concern, connects it to a need, and makes a concrete request. The statement that the broker accepted client order identifier X at 10:04:02 while the Lambda step lacked a success checkpoint is an observation. The concern is duplicate market exposure. The need is a deterministic reconciliation boundary. The request is to stop new submissions for the affected strategy while reconciliation runs. This is more useful than labeling a person careless.
FBI-style tactical empathy contributes de-escalation. During a severe incident, a leader can label the pressure without surrendering the control objective. The team may feel that stopping submission will miss the market and hurt the client. That concern is real. The leader then anchors the next action in verifiable evidence and preserves decision authority. Tactical empathy is not manipulation. It is the disciplined effort to make the other party feel understood so that reasoning can resume under stress.
These cultural ideas should become mechanisms. Every durable step has an owner and documented failure meaning. Every risk override has a reason, expiry, and reviewer. Every incident review includes the strongest contrary interpretation. Every deployment identifies irreversible decisions. Every AI-generated change receives human review and deterministic tests. Every post-incident report separates facts, hypotheses, decisions, and lessons. The institution learns without turning candor into punishment or kindness into weak control.

Governance for AI-assisted coding

AI coding can accelerate implementation, but it can also produce plausible code that misunderstands replay. The model may place Date.now() outside a step, create a new UUID on each invocation, perform a broker call in ordinary code, retry a non-idempotent API blindly, or checkpoint sensitive and oversized payloads. The development standard should therefore include automated checks for non-deterministic calls in the replay path, side-effect adapters outside durable steps, unstable step names, missing callback timeouts, unbounded condition polling, mutable configuration reads, and SDK-version drift.
Stable step names are part of the execution contract. Renaming, reordering, inserting, or deleting operations can affect in-flight executions. Code review must distinguish changes safe for new executions from changes safe for paused historical executions. Versioned aliases provide a boundary. Old versions remain available for existing work, while new traffic moves to the new version after tests. A migration plan is required when a security or correctness defect makes the old version unacceptable.
AI-generated tests should not be trusted merely because they pass. The team should review whether the tests can fail for the intended reason. Replay testing should inject interruption before and after external side effects. Property-based tests should verify book sorting, aggregation, spread, and imbalance across decimals and empty states. Contract tests should verify broker idempotency and status reconciliation. Chaos tests should delay callbacks and deny KMS, DynamoDB, S3, or network access. Security tests should attempt callback forgery, cross-intent approval, stale-token reuse, excessive payloads, and privilege escalation.
The system should keep AI out of final authority where policy does not permit autonomous trading. An LLM can summarize market context, explain risk reasons, classify exceptions, or draft an operations narrative. Its output should be treated as untrusted data, versioned, filtered for sensitive information, constrained by deterministic policy, and reviewed when consequential. A model recommendation never substitutes for pre-trade controls, suitability obligations, best-execution processes, market-abuse surveillance, or accountable human judgment.

The long-term operating model

The first release should be deliberately narrow. It can process a single venue, a controlled instrument set, a three-level snapshot, one order type, and small notional. It should optimize for learning, evidence, and reversibility. The team measures sequence quality, replay frequency, checkpoint volume, approval age, submission uncertainty, execution quality, false risk rejections, and manual intervention. Those measurements decide the next investment.
As volume grows, the institution may split market-data normalization from trade orchestration, move hot state to a specialized low-latency service, add a broker abstraction layer, or place durable coordination above several execution workers. This is not a failure of the single-function beginning. It is the expected evolution of clear boundaries under real load. The initial cohesive function should make those boundaries visible enough to extract.
Success is not the number of AWS services removed. Success is a faster path from intent to controlled outcome, fewer ambiguous states, less duplicate work, lower cognitive load, stronger evidence, safer change, and a team that can confront reality without blame. Lambda Durable Functions provides a powerful mechanism for that goal because it turns sequential application code into a durable workflow. The institution raises the industry bar only when it combines that mechanism with deterministic engineering, market-microstructure humility, independent controls, disciplined cost management, and a culture in which truth moves faster than risk.

Series: Financial Service (19 articles)

  1. …
  2. 5
    Lambda Durable Functions for a Governed Three-Level Order-Book Workflow This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article