Free learning / Gateway lab + shared-budget extension
AI gateways: control a model request before it leaves
An AI gateway sits between your application and model services. Test identity, token budgets and approved routing, then make two workers compete for one shared SQLite budget before mapping the contract to a deployed gateway.
No account needed. Use your own copy for writing and keep the original as a reference.
Engineering lab library / Run locally
Follow a model request through its controls.
Run the local policy exercise, compare an unsafe budget with full reservations, and explain each refusal before mapping it to a gateway product.
Synthetic records. No provider key or model inference. Runs locally with the standard library.
Search titles, outcomes and prerequisites, then narrow by runtime.
2 of 2 labs · All labs
Start here / Python 3.11+ · Standard library
AI gateway admission and token budgets
Compare overlapping reservations, reject forged budget hints and refuse an unapproved fallback.
Python 3.11+ standard library · Offline synthetic requests
Python 3.11+ · Standard library
Shared gateway budget · concurrent SQLite workers
Expose a lost debit, enforce conditional admission, verify rollback and let both smaller requests through.
Python 3.11+ · Standard library · Temporary SQLite · No network or model
An AI gateway is a service that sits between an application and AI backends. It receives requests, applies traffic policies and forwards allowed work to a chosen backend. Think of a reverse proxy with policies for model traffic. It is not a model, an agent framework, or permission to read every customer record.
This original LockedIn FDE lab uses one fictional maintenance assistant to make that boundary concrete. Start with Azure API Management explained or Kong AI Gateway explained for a visual introduction. Allow about 60 minutes for the core lesson, plus 25 minutes for the optional shared-budget experiment in section 4b.
The first Python exercise runs offline with the standard library. It models one sequential, in-memory budget window using supplied identities and token counts. It does not authenticate callers, run a model, implement either vendor's policy, or provide production middleware. A separate SQLite extension runs two real worker threads against one temporary database. No cloud account, credentials or purchase is needed.
1. Put the gateway in the right place
The fictional North maintenance team uses an assistant that drafts a response. Another team, South, uses the same model service. North has a 1,500-token exercise budget; South has 5,000. Those are synthetic limits, not provider prices or quotas.
Follow the request through five responsibilities:
| Step | Responsibility | What crosses the boundary |
|---|---|---|
| 1. Application | Verify the caller and authorize the source records | A trusted identity and permitted context |
| 2. Gateway | Select an approved route and check its budget | A bounded model request |
| 3. Model service | Generate within the selected request limits | Output, completion state and usage when available |
| 4. Application | Validate the result and check citations | A draft with explicit evidence or an error |
| 5. Operator | Accept, revise or reject the proposed business action | A separate human decision |
The gateway's decision is about a particular request. It does not replace document-level authorization, a model-quality evaluation, or approval to send a message. Draw a line around each responsibility. Explain where a model-suggested tenant name would be rejected before following any commands.
2. Run the admission experiment
Download fde-ai-gateway-lab.py to an empty working folder. Use Python 3.11 or later. Check the version first; if your computer uses a versioned command such as python3.11, use that command throughout.
python3 --version
python3 fde-ai-gateway-lab.py test
python3 fde-ai-gateway-lab.py compare
python3 fde-ai-gateway-lab.py compare --candidate prompt-onlyBoth candidates see two overlapping requests before either response arrives. Each request has 400 input tokens and may generate up to 600 output tokens. Predict the decisions before reading the JSON results.
| Candidate | First request | Second request | Maximum admitted use |
|---|---|---|---|
| reserve-output | Reserve 1,000; 500 remain | Refuse: needs another 1,000 | 1,000 |
| prompt-only, intentionally broken | Reserve 400 | Reserve another 400 | 2,000 against a 1,500 budget |
The broken candidate reports 700 tokens remaining while it has admitted work that could exceed the budget. This is the distinction between accounted reservation and possible usage. A successful HTTP response or a green test of one request would not reveal the overlapping-work defect.
Change North's synthetic budget to 2,000 in your copy, rerun both candidates, then restore it. Both can admit two requests, but only one has reserved their full envelope. A passing scenario is not a general proof of the implementation. Keep the original result when recording your changed result.
3. Keep identity, context and quota separate
python3 fde-ai-gateway-lab.py demoRead first, then forged_tenant_hint. The second request asks to use South's identity in its body. The exercise still charges North because verified_tenant comes from the supplied trusted fixture. South retains all 5,000 tokens. In a real service, that fixture must be replaced by authenticated server context; accepting a caller's arbitrary tenant argument would defeat the entire boundary.
Now distinguish three controls:
| Control | The question it answers | What it cannot establish |
|---|---|---|
| Context limit | Can this single request fit the selected model's input/output contract? | Whether the team has enough total budget |
| Request rate | How many calls may arrive in a time window? | The cost or token size of those calls |
| Token budget | How much usage may this scope consume? | Whether the requested source record belongs to this caller |
The lab checks context and a single-window token budget. It does not implement a clock or a request-rate limiter. Input counts are supplied assumptions; a real integration needs the target model's counting method and its documented limits. A token is not a universal word count, a dollar amount or a byte of GPU memory.
4. Do not turn missing usage into zero
The demonstration reserves 1,000 tokens. missing_usage has no provider receipt, so 500 remain and another 1,000-token request is refused. A timeout does not prove that no inference occurred. The conservative reservation stays until reconciled.
Next, a supplied receipt reports 550 actual tokens. confirmed_receipt replaces the reservation with that usage, leaving 950. A smaller request for 400 input plus 500 output tokens fits and leaves 50. Repeating the same receipt does not charge or release it twice; a conflicting receipt is rejected. Usage beyond the reserved envelope or a conflicting settled receipt freezes new admissions for that team. This exercise has no automatic release operation; the inconsistency requires investigation rather than a convenient lower number.
These receipts are synthetic observations, not actual provider measurements. Each new admission is a new request in this exercise; it does not deduplicate client retries or provide provider-side idempotency. Write how your real service would reconcile a lost response without starting a duplicate request. Include who investigates an impossible receipt and what stops more work while it is unresolved.
4a. Follow one receipt through reconciliation
A reservation accounts for admitted work before final usage is known. Settlement replaces that provisional charge with accepted usage evidence. Reconciliation investigates missing or conflicting observations; it is not a reason to invent a convenient number. Keep the arithmetic and the policy state visible together.
python3 fde-ai-gateway-lab.py receiptsThis is a separate run from demo: it follows one reservation and does not admit the extra 900-token request shown there. Each row below is an actual call to a local policy method, using supplied synthetic receipt values. There is no clock, provider message, model execution, money movement or distributed counter.
| Event | Accounted tokens | Arithmetic remaining | Reconciliation required? |
|---|---|---|---|
| Reserve R1 for 400 input + up to 600 output | 1,000 | 500 | No |
| Usage is unknown | 1,000 | 500 | No |
| Confirm 550 for R1 | 550 | 950 | No |
| Repeat the same 550 for R1 | 550 | 950 | No |
| Receive conflicting 400 for R1 | 550 | 950 | Yes |
| Try admitting one more token | 550 | 950 | Yes; request refused |
Inspect result, accounted_tokens, remaining and reconciliation_required. The first 1,000 is an envelope held against the budget, not measured consumption. Unknown usage retains that charge. A supplied 550 replaces it once, releasing 450 from the hold. Repeating the same reservation's receipt must not release another 450. This is idempotent settlement, not deduplication of a new model request: each new admission still creates a new reservation in this program.
The conflicting 400 does not replace 550. North is frozen for investigation even though its arithmetic balance is 950. The next request needs only one token and still returns usage_reconciliation. A positive balance does not override every other policy. This exercise has no automatic release or reconciliation command.
Change the receipt, not the guard
Make a separate copy of the original file. Inside receipt_trace, change only gateway.settle("north", reservation_id, 400) to use 550. Preserve the general settle method and the other events. Predict six outcomes before running the copy. The event retains the label conflicting-400, but its actual result should now be settled: the values match. The final one-token admission should succeed, with 551 accounted and 949 remaining. Earlier events should stay unchanged. Record the edit and actual result; a case label is not evidence of what happened.
As a second reasoning challenge, explain why replacing None with zero would change the observation rather than recover missing evidence. A verified zero could justify release; timeout or a canceled wait alone cannot. That distinction also matters when a worker crashes after dispatch. See the AWS Builders’ Library explanation of timeouts and remote effects, checked 25 October 2026. Retaining a reservation is this lab's conservative policy, not a claim that every gateway implements it.
For a real integration, identify who supplies usage, how it is authenticated and matched to the request, which tokens or other units it covers, and what happens when observations disagree. Write the intended resolution owner and bounded stop behavior before allowing more work. Do not treat a customer-supplied token total as an authoritative provider receipt.
UNDERSTAND THE SYSTEM
A timeout does not put the budget back.
Follow one reservation through six calls to local policy methods. Token counts and receipts are supplied fictional inputs. No model, gateway product, billing system or network request is running; the example has one sequential in-memory budget window.
Watch one example, step by step.
Read the full worked example
- 01Reserve before output
Admitting R1 accounts for its entire 1,000-token envelope. North's 1,500 budget has 500 remaining. This does not mean 1,000 tokens have been consumed; it prevents pending output from disappearing from admission arithmetic.
LOCAL POLICY · RESERVE: Accounted 1,000 · remaining 500 · reconciliation clear
- 02Usage is unknown
The supplied usage value is None. The same reservation stays accounted at 1,000, with 500 remaining. A timed-out client or canceled wait would not by itself prove that the upstream performed no work.
LOCAL POLICY · UNKNOWN: Accounted 1,000 · remaining 500 · reconciliation clear
- 03Confirm 550 tokens
A supplied total of 550 replaces the 1,000 charge, leaving 950. The difference is 450 newly available tokens in this budget; it is not a currency refund or a measured provider receipt.
LOCAL POLICY · SETTLE: Accounted 550 · remaining 950 · reconciliation clear
- 04Repeat the same receipt
Settling R1 at 550 again leaves the balance unchanged. This demonstrates idempotent settlement for one reservation. It does not deduplicate a retried client admission or prevent a second inference request.
LOCAL POLICY · REPEAT: Accounted 550 · remaining 950 · reconciliation clear
- 05Reject a conflicting total
A later supplied total of 400 conflicts with the settled 550. The policy rejects the change, retains 550 and marks North for reconciliation. Accepting the smaller number would rewrite existing evidence; this lab does not decide which receipt was correct.
LOCAL POLICY · CONFLICT: Accounted 550 · remaining 950 · reconciliation required
- 06Refuse even one more token
A new request asks for a one-token envelope. Although 950 remain arithmetically, admission returns usage_reconciliation. No new reservation is created. The hold is a separate policy condition. Resolution needs evidence and an authorized process; this exercise has no release command.
LOCAL POLICY · HOLD: Accounted 550 · remaining 950 · reconciliation required
Read the connections in plain English
- 01Bound the request → Choose trusted scope
Use the trusted caller context, not a generated budget hint.
- 02Choose trusted scope → Hold the envelope
Check route, context and available budget before creating a reservation.
- 03Hold the envelope → Read usage evidence
An admitted request can lack a known final usage result.
- 04Read usage evidence → Keep one accounting state
Apply the current receipt to the same reservation without rewriting a conflict.
- 05Keep one accounting state → Decide about more work
Check both remaining capacity and whether reconciliation has stopped new work.
Check your understanding: Does repeating the same settlement prove that retrying an API request is safe?
No. Settlement idempotency is scoped to the same reservation and matching receipt. Every new admission creates a new reservation in this lab. A receiving system needs its own request identity, durable state, recovery and upstream duplicate-handling contract.
4b. Make admission atomic across workers
The first experiment accounts for the full output envelope, but calls its policy one request at a time. Two workers can each do correct arithmetic against the same old balance and still admit more than the shared limit. This is a different failure from forgetting to reserve output.
Download the shared-budget companion. Use Python 3.11+ and its standard-library SQLite. Read the file first. It creates a temporary local database, starts two worker threads with separate connections, then closes them and removes the database. There is no network, inference, authentication, provider bill or change to your own databases. North and both requests are supplied fixtures. The synchronization barrier deliberately makes both workers read 1,500 before either attempts its write; this is controlled contention, not a load benchmark.
python3 fde-gateway-concurrency.py --all > shared-budget-results.json
python3 fde-gateway-concurrency.py --case unsafe
python3 fde-gateway-concurrency.py --case atomic
python3 fde-gateway-concurrency.py --case rollbackPredict the number of reservations, their sum and the final balance before running. The two requests have different identities and each reserves a supplied 1,000-token envelope. This is cumulative admission, not two workers claiming the same job or a test of API retry deduplication.
| Case | Mechanism | Evidence to inspect |
|---|---|---|
unsafe | Each worker reads 1,500 before its transaction, then writes its old balance minus 1,000. | Two reservation rows total 2,000, but the stored balance says 500. One debit has disappeared. |
atomic | A conditional debit and reservation insert share one write transaction. | One reservation totals 1,000 and 500 remain. The other worker changes zero budget rows and is refused. Either worker may win. |
rollback | A deliberately injected exception occurs after a real debit and before its reservation insert. | The transaction rolls back: 1,500 and no reservation remain. A later attempt can reserve 1,000. This case is sequential. |
A transaction around the two unsafe writes does not repair the earlier read. Both workers can serialize their transactions and still write the same stale 500. The defect is where the admission condition and arithmetic execute, not whether the code contains the word BEGIN.
The corrected candidate evaluates its condition inside the shared database:
UPDATE budgets
SET remaining_tokens = remaining_tokens - ?
WHERE tenant_id = ? AND remaining_tokens >= ?;The actual affected-row count decides whether to insert the reservation. A zero means the conditional debit did not happen; the program must not invent an admission anyway. The debit and insertion commit together. If the second action fails, roll back both. In the rollback report, after-debit-before-insert is the failing connection's own uncommitted view. It is not a saved balance visible to another connection. Read after-rollback and the later retry-committed snapshot separately. SQLite permits only one simultaneous writer; its transaction boundary coordinates these separate connections. That does not establish another database's isolation behavior, a multi-region gateway limit or provider policy.
For this extension's single window, with no settlement, compare two independent facts: the budget row and the sum of committed reservations. The remaining balance should equal the initial budget minus that sum, and should not be negative. Unsafe admission violates both the capacity contract and the accounting agreement. Read the actual stored rows; a green-looking balance on its own conceals the defect.
In a separately named copy, change RESERVATION_TOKENS from 1000 to 700. Run unsafe and atomic again. Both requests now legitimately fit within 1,500. Atomic admission must allow both and leave 100; refusing everything is not a useful repair. Unsafe admission still leaves a misleading stored balance of 800 although its reservations total 1,400. No overspend in that run does not mean the accounting bug is fixed. Keep the original and changed outputs distinct.
For a pod exercise, give the builder the worker code, the reviewer the two accounting rules, and the receiving operator the run commands. Each predicts before discussion. The receiver independently runs the changed copy and points to the stored rows supporting their conclusion. Record the candidate, personal contribution, assistance, receiving action and next owner. The service owner must define the real budget/window/request identity; the storage owner must verify atomicity and failure behavior in the actual deployment.
This extension does not settle usage or simulate process death. Its injected exception is an application rollback, not evidence of crash durability. A real system still needs request-retry identity, crash recovery, unknown-usage handling, window rollover and a policy for counter-store unavailability. A Python mutex around one process cannot establish a budget shared across other processes or machines. The existing receipt exercise and this database exercise answer different questions and are not a combined deployed gateway.
Primary references checked 26 October 2026: SQLite transactions, visibility between connections, and Python sqlite3 transaction control. The scenario, code, arithmetic and exercise are original LockedIn Labs work.
UNDERSTAND THE SYSTEM
Two workers. One budget that must agree.
Follow two distinct reservations through a shared local SQLite database. These authored frames explain the downloadable experiment; worker timing and the winning request are not predicted.
Watch one example, step by step.
Read the full worked example
- 01Both reads fit
Each worker sees 1,500 and proposes 1,000. Each request fits alone. The barrier establishes this controlled interleaving; two positive local decisions do not establish shared capacity.
BEFORE WRITES: 1,000 + 1,000 requested · shared budget 1,500
- 02The lost debit
The unsafe candidate writes 500 from each stale read. Two reservations commit, totaling 2,000. The stored 500 disguises an effective remaining balance of −500. Serializing writes did not repair the old input.
UNSAFE · ORIGINAL INPUT: Stored 500 · reserved 2,000 · expected −500
- 03One atomic admission
The conditional debit and reservation share one transaction. One worker changes a budget row and commits 1,000; the other changes zero rows and is refused. Either worker can win. Both accounting views leave 500.
ATOMIC · ORIGINAL INPUT: One admitted · one refused · remaining 500
- 04Roll back the pair
A deliberately injected application exception after the debit rolls back the transaction before insertion. The separate sequential rollback case observes 1,500 with no reservation, then admits a later request. This is not a process-crash test.
ROLLBACK · BEFORE LATER ADMISSION: Remaining 1,500 · zero reservations
- 05Let useful work through
Change each request to 700 in a separate copy. Atomic admission allows both and leaves 100. Unsafe admission also allows both but stores 800 against a reserved total of 1,400. A nonnegative balance alone does not prove correct accounting.
CHANGED INPUT · 700 EACH: Atomic 100 remaining · unsafe stores 800
Read the connections in plain English
- 01Worker A → Admission condition
A proposes its supplied token envelope.
- 02Worker B → Admission condition
B proposes a different request against the same budget.
- 03Admission condition → Shared budget row
The atomic condition checks and subtracts in shared storage.
- 04Shared budget row → Committed reservations
Commit the debit and reservation together, or roll both back.
- 05Committed reservations → Reconcile both views
Compare the actual reservation total with the stored balance.
Check your understanding: If the unsafe case reports a positive balance, has it protected the shared budget?
No. Inspect the committed reservation rows and reconcile their sum with the stored balance. Two stale check-then-write decisions can erase a debit. The 700-token variation still exposes inconsistent accounting even though the two requests fit within the budget.
5. Refuse a convenient but unapproved fallback
In unapproved_fallback, the alternate model route is known, but its processing location is outside North's allowed set. The result is location_not_allowed. A healthy backup endpoint is not automatically an approved destination.
An approved location in this fixture is a label in a teaching policy, not proof of a provider's processing, logging or retention behavior. For a real workload, verify the exact offering and agreement. The backend still checks resource access.
Add a second approved route to your own copy. Test both legitimate fallback and the refused route. Do not remove the refusal merely to make every test green. Keep request metadata in the comparison; do not add real prompts or credentials.
6. Translate the reasoning into APIM or Kong
This exercise's reservation algorithm is original teaching code. It is not a claim that a gateway product enforces the same algorithm or a perfectly global cap. Use current documentation for the actual deployment, version and traffic format.
Azure API Management. The documented llm-token-limit policy supports per-key token rates and quotas. Prompt estimation, streaming and concurrent requests affect counting; concurrent work may exceed a configured limit before responses update it. The documentation also distinguishes accounting across gateway instances. Choose the key from trusted context and verify the applicable tier and backend schema. See Microsoft's policy reference.
Kong. The current AI Rate Limiting Advanced policy documents local, cluster and Redis counter strategies, with topology and synchronization tradeoffs. The AI Gateway 2.0 policy and the older Gateway plugin are different versioned surfaces; verify the exact offering rather than copying an unrelated example. See the current policy and Gateway plugin documentation. These references were checked on 25 October 2026.
Create a small mapping table with: requirement, product/version, documented mechanism, deployment scope, evidence still needed and test case. Include caller identity, allowed backends, processing location, token accounting, counter sharing, streaming, missing usage and overload. Leave unsupported or untested rows unknown. Neither reading a policy page nor running this offline lab proves a cloud configuration.
7. Produce a reviewable gateway decision
Keep the original comparison, your one changed scenario, and the provider mapping. Add a diagram showing where trusted identity enters and where resource access remains. Write one useful request that must pass, one forged identity hint that must fail, one overlapping-budget case and one forbidden fallback. State what observations would make you change the policy rather than weakening an expected result.
Ask a peer to explain the difference between a model, an agent and a gateway using your diagram. Then ask them to predict the second admission before running it. If the explanation does not support that prediction, repair the explanation first.
Continue with AI gateway 101: route, reserve and reconcile using your training access. The protected lesson adds explanation, diagnosis and design rehearsals. Use section 4b to inspect shared local admission, then identify the still-unproven process-loss, usage-settlement and window-boundary behavior in your receiving environment.