<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Raviteja Kapalavayi on Medium]]></title>
        <description><![CDATA[Stories by Raviteja Kapalavayi on Medium]]></description>
        <link>https://medium.com/@teja230?source=rss-895cec4be077------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*PprMM1py3iVNREaO.</url>
            <title>Stories by Raviteja Kapalavayi on Medium</title>
            <link>https://medium.com/@teja230?source=rss-895cec4be077------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:47:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@teja230/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Your AI Agent Needs an SLO, Not a Demo]]></title>
            <link>https://medium.com/@teja230/your-ai-agent-needs-an-slo-not-a-demo-c8fdbf8ccef6?source=rss-895cec4be077------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8fdbf8ccef6</guid>
            <dc:creator><![CDATA[Raviteja Kapalavayi]]></dc:creator>
            <pubDate>Fri, 20 Nov 2026 15:01:02 GMT</pubDate>
            <atom:updated>2026-11-20T15:01:02.247Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Measure verified business outcomes, trace tool decisions, and page on mistakes that HTTP status codes cannot see.</em></p><p>Imagine a shopping agent with a clear instruction: buy these items, make no substitutions, and spend no more than $100 including tax and shipping. It creates the cart, applies a coupon, submits payment, and confirms the order.</p><p>Every API returns successfully. The customer gets charged $104.</p><p>Your dashboard is green. Your customer has a reasonable objection.</p><p>I don’t consider an agent ready for autonomous production writes until we can measure whether its actions satisfied the customer’s authorized request. Model latency and API availability still matter, but neither establishes that the agent did the right thing.</p><p>That requires a reliability contract outside the agent’s own narration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lscv5YPmSyy8eENo-fx8rQ.png" /></figure><h3>1. Give the task a success contract</h3><p>For this hypothetical purchase workflow, I’d start with an illustrative SLO: <strong>99% of admitted purchase tasks produce a verified, compliant order and truthful confirmation within 60 seconds, measured over 30 days.</strong></p><p>Those numbers are design assumptions, not a recommended industry benchmark.</p><p>“Compliant” means the correct customer, exact approved items and quantities, an authorized payment amount, and no duplicate order. A fast order that exceeds the spending limit fails. So does a confident confirmation for an order that never committed.</p><p>Before execution, bind the task to the authenticated customer and preserve the approved constraints. For consequential details such as spending limits and substitutions, get explicit confirmation of the structured request. Otherwise, the agent and evaluator can agree perfectly on a misinterpretation.</p><p>The denominator deserves as much attention as the success rule. Count every admitted task once, including tasks that time out, crash, or require human rescue. Three retries belong to the same task. They do not create three fresh opportunities to report success.</p><p>Define admission rules in advance and monitor rejection rates separately. An agent that refuses every difficult request can otherwise acquire an impressive reliability score and no useful customers.</p><p>A safe refusal after admission still misses this purchase-completion SLO. That is acceptable: refusing an unsafe purchase is the correct behavior, while the product still failed to complete the requested purchase. Track safety and completion separately.</p><p>At 10,000 admitted tasks, a 99% target allows 100 failed tasks. It does not grant permission for 100 unauthorized charges. Certain violations need immediate action regardless of the remaining error budget.</p><h3>2. Trace execution, then record the outcome independently</h3><p>A useful trace follows the work: task orchestration, model requests, catalog lookup, pricing, inventory reservation, payment, order creation, and verification.</p><p>Record each tool attempt separately, with its duration, redacted arguments, domain result, retry number, and authorization decision. “Payment API returned 200” and “payment was declined” must remain distinguishable. So must “payment succeeded” and “payment exceeded the approved limit.”</p><p>For a Spring Boot service, Datadog’s <a href="https://docs.datadoghq.com/llm_observability/instrument/sdk/?utm_source=chatgpt.com">Agent Observability SDK</a> provides Java methods for LLM and tool spans. Instrument the actual tool execution boundary, not merely the model’s request to call a tool. <a href="https://docs.datadoghq.com/llm_observability/instrument/sdk/?utm_source=chatgpt.com">docs.datadoghq.com</a></p><p>Keep a stable task ID across retries, asynchronous workers, and resumed execution. Propagate trace context through Kafka where appropriate; use the task ID to correlate work that spans multiple traces.</p><p>Attach model, prompt, tool-schema, and policy versions. A regression after a deployment might come from a changed tool description rather than a changed model.</p><p>But a trace should not be the only record that a task existed.</p><p>I’d persist task admission and outcome evidence in an application-owned ledger. Store outcome changes and an outbox event in the same database transaction, then publish asynchronously. Deduplicate consumed events by stable event ID, and enforce task transitions with a version check or database constraint.</p><p>That transaction covers your database, not the external payment provider. Provider idempotency and reconciliation remain necessary.</p><p>Compute the SLI from admission cohorts whose 60-second deadline has passed. Every admitted task gets classified, including abandoned ones. Missing verification becomes an explicit failure to verify, never an implicit success.</p><p>Export these counts independently of trace sampling. Keep task IDs in traces and the ledger; use bounded metric tags such as workflow, release, and outcome.</p><p>One Datadog detail is easy to miss: arbitrary numeric values attached to spans do not automatically become platform metrics. Its <a href="https://docs.datadoghq.com/llm_observability/instrument/sdk/?utm_source=chatgpt.com">SDK documentation</a> distinguishes span annotations from recognized fields that generate metrics. Publish your task-level good and total counts deliberately. <a href="https://docs.datadoghq.com/llm_observability/instrument/sdk/?utm_source=chatgpt.com">docs.datadoghq.com</a></p><h3>3. Verify the business state, not the agent’s explanation</h3><p>A semantic failure is an execution that completed technically but violated the task’s meaning. The $104 purchase is one. Buying the wrong quantity is another.</p><p>My first evaluator would be ordinary code.</p><p>Here is a partial Java 17 verifier for the spending-limit check alone:</p><pre>enum BudgetVerdict {<br>    PASS, OVER_BUDGET, CURRENCY_MISMATCH, UNKNOWN<br>}</pre><pre>record Budget(String currency, long maxMinor) {}<br>record Payment(String currency, long committedMinor) {}</pre><pre>static BudgetVerdict checkBudget(Budget budget, Payment payment) {<br>    if (payment == null) {<br>        return BudgetVerdict.UNKNOWN;<br>    }<br>    if (!budget.currency().equals(payment.currency())) {<br>        return BudgetVerdict.CURRENCY_MISMATCH;<br>    }<br>    return payment.committedMinor() &lt;= budget.maxMinor()<br>            ? BudgetVerdict.PASS<br>            : BudgetVerdict.OVER_BUDGET;<br>}</pre><p>This assumes validated, nonnegative amounts in the currency’s minor unit. The budget comes from approved intent; the payment comes from authoritative payment records and includes all committed amounts for the task, not just the latest attempt. Identity, quantities, duplicates, and confirmation accuracy require separate checks.</p><p>The same spending constraint also belongs at the write boundary. Enforce it against the final payable amount, with atomic budget reservation where concurrent purchases share a limit. An asynchronous evaluator detects escaped violations; it cannot prevent a charge already made.</p><p>Some judgments need more than arithmetic. Did a substitution satisfy a vague preference? Did the explanation accurately describe a delivery restriction? An LLM judge can help assess those cases, but I’d calibrate it against human-reviewed examples and record the evaluator’s version.</p><p>The judge should receive trusted evidence, with agent-generated explanations treated as untrusted input. Asking the agent whether it succeeded mostly measures its willingness to say yes.</p><p>Datadog supports <a href="https://docs.datadoghq.com/llm_observability/investigate/evaluations/external_evaluations/?utm_source=chatgpt.com">external evaluations associated with spans, traces, or sessions</a>. That makes it possible to connect an independent business verdict to execution evidence. <a href="https://docs.datadoghq.com/llm_observability/investigate/evaluations/external_evaluations/?utm_source=chatgpt.com">docs.datadoghq.com</a></p><p>Keep deterministic checks exhaustive where practical. For expensive semantic reviews, report sampling coverage and evaluator errors alongside the pass rate. Evaluating only suspicious traces does not produce an unbiased fleet-wide success rate.</p><p>Delayed evidence needs special treatment. A reconciliation job might discover a duplicate charge after the original trace ended. Preserve the correction against the original task and recompute its historical cohort; an increment-only success counter cannot undo yesterday’s verdict.</p><p>And if you refund the duplicate, record the recovery separately. Repairing the harm does not make the original action correct.</p><h3>4. Monitor cost per verified success</h3><p>Token count tells me where work happened. Cost per successful task tells me whether that work was worth doing.</p><p>For a given task cohort, divide the total agent operating cost across all tasks by the number of verified successful tasks. Include failed attempts, retries, fallback models, retrieval, and evaluation. Keep model spend and other operating costs visible as separate components.</p><p>Consider an illustrative comparison across two equivalent batches of 100 tasks. Version A spends $36 and completes 90 correctly: $0.40 per success. Version B spends $20 but completes only 40 correctly: $0.50 per success.</p><p>The cheaper batch produced the more expensive useful outcome.</p><p>Datadog’s <a href="https://docs.datadoghq.com/llm_observability/investigate/cost/?utm_source=chatgpt.com">cost monitoring documentation</a> describes estimates based on recorded token usage and provider pricing, with support for manually supplied costs. These estimates are useful operational signals; reconcile them against actual billing and contracted rates. <a href="https://docs.datadoghq.com/llm_observability/investigate/cost/?utm_source=chatgpt.com">docs.datadoghq.com</a></p><p>Capture cache reads, cache writes, and ordinary input tokens distinctly when the provider exposes them. Applying the standard input rate to every token can distort estimated cost. Also check for missing usage: absent token data should not look like a free request. <a href="https://docs.datadoghq.com/llm_observability/investigate/cost/?utm_source=chatgpt.com">docs.datadoghq.com</a></p><p>Watch the distribution, not just the average. A small fraction of tasks can loop through tool calls while the median remains reassuring.</p><p>Set per-task limits on elapsed time, model calls, and spend. In concurrent workflows, reserve budget before launching parallel calls so each branch cannot independently spend the same remaining allowance. On exhaustion, stop safely and report the incomplete outcome; do not invent a cheaper approximation of the customer’s authorization.</p><h3>5. Page on incorrect actions, not just exceptions</h3><p>I want two alert paths: sustained degradation in task success, and specific actions that require immediate containment.</p><p>For the first, use error-budget burn rates. With the illustrative 99% SLO, a 5% bad-task rate burns budget at five times the allowed rate.</p><p>Google’s <a href="https://sre.google/workbook/alerting-on-slos/?utm_source=chatgpt.com">SRE workbook</a> recommends combining long and short windows to detect sustained problems while checking that they are still happening. Datadog’s <a href="https://docs.datadoghq.com/service_level_objectives/burn_rate/?utm_source=chatgpt.com">burn-rate alerts</a> support this pattern. <a href="https://sre.google/workbook/alerting-on-slos/?utm_source=chatgpt.com">Prometheus Alerting: Turn SLOs into Alerts</a></p><p>For a 30-day target, a starting configuration could page at 14.4-times burn across both one hour and five minutes, plus a slower condition at six-times burn across six hours and 30 minutes. Tune those thresholds to traffic and business impact. Sparse task volumes need particular care; one failure can dominate a percentage. <a href="https://sre.google/workbook/alerting-on-slos/?utm_source=chatgpt.com">Prometheus Alerting: Turn SLOs into Alerts</a></p><p>For the second path, a confirmed unauthorized charge, cross-customer action, or duplicate purchase should trigger an incident without waiting for a rate threshold. A blocked attempt belongs in a separate signal from an executed violation.</p><p>The alert should include the violated rule, affected release, task reference, evidence, and containment action. For a purchase agent, that might mean disabling order submission for the affected workflow while preserving read-only assistance.</p><p>A low-confidence semantic judge score usually belongs in a review queue, not an immediate production shutdown. Different evidence deserves different operational authority.</p><p>Monitor the evaluator too. If its queue stalls, the system has lost visibility into correctness. Deadline-expired tasks must remain visible as unverified, with a separate alert for verification lag.</p><p>This contract is excessive for a brainstorming assistant whose drafts a person always reviews. A research assistant may need citation and human-acceptance measures rather than deterministic order checks. A workflow that legitimately waits hours for approval needs separate measures for that wait and subsequent execution.</p><p>But once an agent can commit money, change permissions, or modify customer state, successful API calls are an inadequate release criterion.</p><p>Tomorrow, choose one write-capable agent workflow and make its success metric depend on an independently verified business outcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8fdbf8ccef6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Rate Limits Are a Backpressure Problem]]></title>
            <link>https://medium.com/@teja230/ai-rate-limits-are-a-backpressure-problem-763cf8bc37a2?source=rss-895cec4be077------2</link>
            <guid isPermaLink="false">https://medium.com/p/763cf8bc37a2</guid>
            <dc:creator><![CDATA[Raviteja Kapalavayi]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 15:01:02 GMT</pubDate>
            <atom:updated>2026-11-18T15:01:02.944Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Use bounded admission, tenant scheduling, and explicit retry budgets to keep AI throttling from becoming an application outage.</em></p><p>Imagine an AI shopping assistant receiving 40 requests per second while its model provider can sustain five. The application queues every request, retries throttled calls, and reports that it is “handling the burst.”</p><p>It is accumulating promises it cannot keep.</p><p>My claim is simple: repeated AI throttling should first trigger a review of admission control. Adding retries before deciding how much work the system can accept makes overload harder to escape.</p><p>The useful lesson from Kafka is that downstream capacity must influence upstream consumption. That applies even when the downstream system generates product descriptions instead of processing order events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ODxrOVJaLMf05kx0KjKxA.png" /></figure><h3>1. Separate the budgets before tuning them</h3><p>An AI endpoint consumes several resources at once: request starts, input tokens, output tokens, active connections, and memory holding unfinished work.</p><p>These limits are related, but they are not interchangeable. <a href="https://platform.claude.com/docs/en/api/rate-limits?utm_source=chatgpt.com">Anthropic’s rate-limit documentation</a>, for example, describes separate request, input-token, and output-token limits. Provider accounting also varies, including how cached tokens count. <a href="https://platform.claude.com/docs/en/api/rate-limits?utm_source=chatgpt.com">Claude Platform Docs</a></p><p>A semaphore controls concurrent calls. It does not enforce requests per minute. If calls suddenly become faster, the same semaphore permits more starts per second.</p><p>Consider an illustrative workload with 20 concurrent calls and four-second average call duration. Concurrency permits roughly five completions per second. If the applicable token budget supports only three requests per second at that workload’s average token usage, three is the planning ceiling.</p><p>That estimate assumes a stable request mix and excludes retries. It is not a latency guarantee. Long outputs, provider slowdowns, and uneven arrivals all change the result.</p><p>I use separate budgets for outstanding logical requests, active attempts, and request/token consumption over time. Every attempt must satisfy the relevant budgets before it starts.</p><p>For token admission, reserve a conservative input estimate and a capped output allowance. Treat that reservation as an application policy; do not assume it reproduces the provider’s billing or throttling algorithm. Conservative reservations waste some capacity, while optimistic estimates increase rejection risk.</p><p>Streaming does not change the accounting boundary. Keep the active slot until the stream finishes or the transport terminates, even if the first token arrived quickly.</p><h3>2. A queue is a latency commitment</h3><p>At three completions per second, 30 waiting requests represent roughly ten seconds of queue-drain time, assuming sustained throughput. A large queue can therefore violate the product’s latency target while memory usage still looks comfortable.</p><p>I choose queue capacity from acceptable waiting time, then check the memory cost. Payload size needs its own limit: 100 queued prompts is not a meaningful memory bound if each prompt can contain an arbitrary document.</p><p>Admission must happen before expensive prompt assembly, retrieval fan-out, or executor submission. Otherwise, the application has already spent resources before reaching the protective gate.</p><p>When admission fails, the product needs a defined outcome. A shopping assistant might return a deterministic catalog result. A description-generation job might accept deferred processing through a bounded, durable backlog. An HTTP API can distinguish tenant quota exhaustion from temporary service overload in its error contract.</p><p>Returning 202 Accepted is appropriate only after the system has actually accepted responsibility for durable work.</p><p><a href="https://kafka.apache.org/41/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html?utm_source=chatgpt.com">Kafka’s consumer flow-control API</a> provides pause() and resume() for assigned partitions. In a Kafka-backed AI pipeline, I pause intake when local capacity is exhausted, keep polling to maintain consumer liveness, and resume as capacity returns. Offset commits must follow the chosen durable processing boundary; handing a record to an in-memory worker is insufficient. <a href="https://kafka.apache.org/41/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html?utm_source=chatgpt.com">kafka.apache.org</a></p><p>Moving the backlog into Kafka does not remove the capacity problem. It changes where the backlog lives. Retention, job expiration, and acceptable lag still need limits.</p><p>For an interactive request, rejecting work that cannot finish in time is often the more honest contract.</p><h3>3. Retries must compete for capacity</h3><p>Suppose the application allows three total attempts and the SDK independently allows three. One logical request can generate up to nine provider calls. Those are illustrative settings, but the multiplication is ordinary arithmetic.</p><p>I give one layer ownership of retries and disable overlapping retry behavior elsewhere.</p><p>Then I add a retry budget shared across requests. A per-request attempt limit cannot stop thousands of requests from retrying together. <a href="https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html?utm_source=chatgpt.com">AWS’s retry documentation</a> describes a separate token-bucket retry quota; the useful principle is to constrain aggregate retry traffic independently of first attempts. <a href="https://docs.aws.amazon.com/sdkref/latest/guide/feature-retry-behavior.html?utm_source=chatgpt.com">AWS SDKs and Tools</a></p><p>Jitter spreads attempts over time. It does not reduce the amount of work promised to callers.</p><p>Here is the more easily missed distinction: a delayed retry releases its active-call slot but retains its outstanding-request slot. When eligible again, it goes through tenant scheduling and all attempt budgets again.</p><p>Otherwise, the “bounded queue” simply spills into a retry scheduler. Java’s <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/ScheduledThreadPoolExecutor.html?utm_source=chatgpt.com">ScheduledThreadPoolExecutor documentation</a> explicitly describes its unbounded queue. A fixed number of scheduler threads does not bound delayed tasks. <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/ScheduledThreadPoolExecutor.html?utm_source=chatgpt.com">docs.oracle.com</a></p><p>Honor a valid provider retry delay, then add jitter to avoid synchronized restarts. Abandon the retry if the delay exceeds the request’s remaining deadline. Classify errors before retrying: invalid input, exhausted spending limits, and transient throttling require different responses.</p><p>A timed-out call is also ambiguous. The provider might have received it. Retrying generation can duplicate cost; replaying a workflow that performs purchases can duplicate side effects. <a href="https://aws.amazon.com/builders-library/timeouts-retries-and-backoff-with-jitter/">AWS’s guidance on timeouts and retries</a> makes the same distinction: failure to receive a response does not prove the operation did nothing. <a href="https://builder.aws.com/content/3EumjoZascWd1oZiEgL8ORlv3qE/timeouts-retries-and-backoff-with-jitter?utm_source=chatgpt.com">builder.aws.com</a></p><h3>4. Make the limits executable in Java 17</h3><p>My Java implementation uses a fixed number of workers, one deque per configured tenant, and a shared admission counter. Workers rotate through eligible tenants. Delayed retries remain in those same bounded deques with a future eligibility timestamp.</p><p>There is no separate executor queue or per-retry scheduled task.</p><p>This illustrative configuration permits eight active attempts, at most two per tenant, and 32 outstanding requests including running work and delayed retries:</p><pre>var gate = new FairAiGate(<br>    Set.of(&quot;merchant-a&quot;, &quot;merchant-b&quot;, &quot;merchant-c&quot;, &quot;merchant-d&quot;),<br>    new FairAiGate.Limits(8, 2, 32, 8, 3),<br>    new FairAiGate.Rate(4, 2),       // Starts/sec, burst<br>    new FairAiGate.Rate(8_000, 16_000), // Input tokens<br>    new FairAiGate.Rate(2_000, 4_000),  // Output tokens<br>    new FairAiGate.Rate(1, 2));      // Retry starts</pre><p>These are local policy values, not provider defaults. In Spring Boot, create one gate for the relevant capacity domain and close it during shutdown. Constructing one per HTTP request defeats the limits.</p><p>The admission section below is an excerpt from submit(). Validation has already checked the request’s token bounds and deadline. The lock makes the capacity check and reservation atomic:</p><pre>synchronized (lock) {<br>    Tenant tenant = tenants.get(tenantId);<br>    if (tenant == null) throw new SecurityException(&quot;Unknown tenant&quot;);<br>    if (closed || outstanding &gt;= limits.outstanding()<br>            || tenant.outstanding &gt;= limits.tenantOutstanding())<br>        throw new RejectedExecutionException(&quot;AI capacity exhausted&quot;);<br>    long now = System.nanoTime();<br>    Job job = new Job(tenant, inputTokens, maxOutputTokens,<br>            call, now + timeout.toNanos(), now);<br>    outstanding++;<br>    tenant.outstanding++;<br>    tenant.queue.addLast(job);<br>    lock.notifyAll();<br>    return job.result.minimalCompletionStage();<br>}</pre><p>The tenant ID must come from authenticated server-side context. A caller-controlled header cannot define the fairness boundary.</p><p>Before dispatch, workers check the deadline, tenant concurrency, and request/input/output budgets under the same lock. Retries also consume a retry token. Network calls happen outside the lock.</p><p>The implementation conservatively charges every attempt’s reservations without refunds. An actual provider adapter must cap output, bound input, enforce the supplied remaining timeout, and disable hidden SDK retries.</p><p>This retry-delay helper adds bounded exponential jitter after the provider’s minimum delay. The implementation caps request deadlines at ten minutes:</p><pre>static long retryDelayNanos(int failedAttempts, Duration retryAfter) {<br>    long ceilingMs = Math.min(2_000L,<br>            200L &lt;&lt; Math.min(10, failedAttempts - 1));<br>    long jitter = ThreadLocalRandom.current().nextLong(ceilingMs + 1);<br>    if (retryAfter.compareTo(Duration.ofMinutes(10)) &gt;= 0)<br>        return Duration.ofMinutes(10).toNanos();<br>    return retryAfter.toNanos()<br>            + TimeUnit.MILLISECONDS.toNanos(jitter);<br>}</pre><p>The completion path releases the active slot after the attempt returns. A retry keeps its admission reservation; a terminal outcome releases it.</p><p>That distinction matters with <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/CompletableFuture.html?utm_source=chatgpt.com">CompletableFuture</a>. Timing out the caller’s future does not establish that the underlying HTTP operation stopped. Releasing capacity at that moment can admit additional calls while the original calls remain active. <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/CompletableFuture.html?utm_source=chatgpt.com">docs.oracle.com</a></p><p>The gate checks deadlines at dispatch and completion; it does not forcibly terminate a misbehaving client. Its concurrency bound covers local attempts, not remote execution after a connection disappears.</p><p>The implementation was compiled with Java 17 and passed simulated-call checks covering admission, tenant isolation, dispatch order, delayed retries, deadlines, shutdown, and all four rate budgets. Those checks do not validate a provider integration.</p><h3>5. Fairness needs a unit, and limits need a scope</h3><p>A global FIFO queue lets a busy tenant place hundreds of requests ahead of a quieter tenant. Per-tenant admission caps limit that damage; round-robin dispatch gives eligible tenants turns.</p><p>But equal turns are not equal resource shares. One tenant might generate 50-token answers while another generates 5,000-token reports.</p><p>The implementation provides fairness between eligible request starts. It does not guarantee equal token consumption or waiting time. Large requests can also lose repeatedly to smaller requests that fit the remaining token budget.</p><p>For widely varying costs, I would add weighted deficit scheduling using estimated token cost, reconcile against observed usage, and introduce aging or reserved capacity for large jobs. Tenants with contractual service guarantees also need reserved admission capacity; fair dispatch cannot help a request that was rejected before entering the queue.</p><p>Scope matters just as much. Ten replicas with an eight-call local limit permit up to 80 local attempts. Shared provider quotas need a central admission service, atomic shared counters, or explicitly partitioned budgets. Autoscaling application pods does not increase provider capacity.</p><p>I monitor oldest queued age, deadline expirations, active calls, retry attempts per logical request, and rejection rates by tenant class. A falling 429 count is poor evidence of success if callers are waiting longer inside the application.</p><p>For a small internal tool, a bounded executor and a concurrency cap may be enough. For overnight batch generation, a durable queue and a longer completion target may be appropriate. Custom tenant scheduling earns its complexity when workloads compete for scarce shared capacity.</p><p>Tomorrow, make one overload test exceed your AI endpoint’s sustainable throughput and verify that accepted work stays bounded while a quiet tenant still makes progress.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=763cf8bc37a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why AI Agents Need Workflow Engines]]></title>
            <link>https://medium.com/@teja230/why-ai-agents-need-workflow-engines-8e2707379c1b?source=rss-895cec4be077------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e2707379c1b</guid>
            <dc:creator><![CDATA[Raviteja Kapalavayi]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 15:01:04 GMT</pubDate>
            <atom:updated>2026-11-16T15:01:04.057Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Durable execution keeps a useful plan from becoming a duplicate payment, an abandoned reservation, or an approval nobody can explain.</em></p><p>Imagine a shopping agent placing a hypothetical $240 order. The payment provider authorizes the amount, but the worker crashes before recording the response. After restarting, the agent sees no confirmation and tries again with a new payment identifier.</p><p>The model can reason perfectly about the customer’s intent and still create two payment authorizations.</p><p>My position is straightforward: an agent coordinating a business transaction across services should execute through a durable workflow. The model can propose the next action. Code must enforce whether that action is allowed, and durable state must determine what remains unfinished.</p><p>Conversation history cannot carry that responsibility by itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d7y6IFtNdEP-Thhr8n8Z0g.png" /></figure><h3>1. Give the workflow ownership of unfinished business</h3><p>Consider a hypothetical Spring Boot checkout service. An agent selects an acceptable product substitution, the customer approves the resulting quote, and the system reserves inventory, authorizes payment, and submits the order.</p><p>The difficult part is everything between those steps: a reservation expires, a payment response disappears, or approval arrives after the price changes.</p><p>I separate three kinds of state. Conversation state captures the customer’s request. Domain state records inventory, payments, and orders. Execution state records which operation was requested, its known outcome, and what should happen next.</p><p>The workflow owns execution state. The inventory and payment services remain authoritative about their resources.</p><p>In this design, Spring Boot authenticates the request and starts a workflow using an identifier bound to the tenant and business operation. Repeated submissions resolve to that operation. Activity workers call the model and business APIs, while Kafka carries domain events between services.</p><p>The model proposes a substitution. Application code validates product eligibility, spending limits, and customer authorization. Downstream APIs enforce their own authorization and concurrency rules before changing anything.</p><p>I also bound the agent’s freedom: permitted actions, maximum planning iterations, spending limits, and an overall deadline. A durable infinite loop is still an infinite loop. It just survives deployments.</p><p>Durability makes this separation useful. Temporal, for example, records an <a href="https://docs.temporal.io/encyclopedia/event-history?utm_source=chatgpt.com">execution history of workflow events</a> that workers can use to recover progress after a crash. The application still has to define what that progress means. <a href="https://docs.temporal.io/encyclopedia/event-history?utm_source=chatgpt.com">Temporal Documentation</a></p><p>“Payment outcome unknown” deserves an explicit state. Treating it as “payment failed” is how recovery becomes a second purchase attempt.</p><h3>2. Replay must preserve decisions already made</h3><p>A model call is an external operation. Putting it directly inside replayed workflow logic risks getting a different answer while reconstructing an earlier execution.</p><p>Temporal’s <a href="https://docs.temporal.io/workflow-definition?utm_source=chatgpt.com">determinism requirements</a> place network calls, database queries, and LLM invocations in Activities. Workflow logic then operates on their recorded results. <a href="https://docs.temporal.io/workflow-definition?utm_source=chatgpt.com">Temporal Documentation</a></p><p>Suppose the agent chose substitution B, and the customer approved it. Recovery must preserve that choice. Asking the model again might produce substitution C, leaving the system executing a plan the customer never approved.</p><p>Temporal’s <a href="https://docs.temporal.io/workflows?utm_source=chatgpt.com">replay behavior</a> reuses recorded Activity results while rebuilding workflow state. A completed model call with a recorded result therefore does not need to run again during replay. <a href="https://docs.temporal.io/workflows?utm_source=chatgpt.com">Temporal Documentation</a></p><p>That guarantee has an edge: the model may return successfully before the worker records completion. Retrying that Activity can make another model call.</p><p>For that reason, I keep planning Activities free of business mutations. A repeated planning call may cost money or produce another candidate, but it must not independently reserve inventory or authorize payment. The workflow selects the recorded proposal, validates it, and schedules effects separately.</p><p>This distinction matters even when a model provider offers tool calling. A planning response can contain proposed tool calls without immediately executing them.</p><p>I retain the accepted structured plan, its version, and relevant model and policy identifiers. A deliberate replan creates a new plan version, with fresh approval when the authorized terms change.</p><p>Deployments need the same care. Changing the sequence of workflow commands can invalidate replay of existing histories. Version workflow changes, and replay representative histories before rolling them out. <a href="https://docs.temporal.io/workflow-definition?utm_source=chatgpt.com">Temporal Documentation</a></p><p>A workflow paused for a customer’s decision is still a consumer of yesterday’s code.</p><h3>3. Kafka events need an execution owner</h3><p>Kafka can tell the system that inventory was reserved. The application still needs an owner for deciding whether that reservation belongs to an active checkout, has already been consumed, or must be released.</p><p>I use Kafka for distributing business facts and the workflow for tracking the consequences of those facts for one operation.</p><p>A payment service might publish PaymentAuthorized with a business operation ID, payment attempt ID, and event ID. A consumer routes it to the matching workflow. The workflow checks whether the event advances its current state and deduplicates repeated delivery.</p><p>Acknowledgment order matters. If the consumer commits its Kafka offset before the workflow durably accepts the event, a crash can lose the handoff. If it delivers first and crashes before committing, Kafka can redeliver. I prefer the latter with explicit deduplication.</p><p>The database-to-Kafka boundary needs protection too. A <a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html?utm_source=chatgpt.com">transactional outbox</a> lets a service write its business change and outgoing event in one local database transaction. A separate publisher delivers the event; consumers still handle duplicates. <a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html?utm_source=chatgpt.com">AWS Prescriptive Guidance</a></p><p>Kafka transactions do not automatically make a payment API call atomic with a consumed offset. Kafka’s <a href="https://kafka.apache.org/42/design/design/?utm_source=chatgpt.com">delivery semantics documentation</a> explicitly distinguishes processing within Kafka from effects in external systems, which require cooperation from those systems. <a href="https://kafka.apache.org/42/design/design/?utm_source=chatgpt.com">Apache Kafka</a></p><p>Replaying a topic also needs a purpose. Rebuilding an analytics projection should not accidentally reissue payment commands. I separate projection consumers from consumers authorized to advance business workflows.</p><p>A team can implement this coordination with Kafka, PostgreSQL, and scheduled workers. Once it adds durable timers, transition guards, retry policies, and recovery tooling, it is maintaining a workflow engine of its own.</p><p>That can be a reasonable choice. It should be a deliberate one.</p><h3>4. Timeouts create uncertainty; compensation creates more work</h3><p>A timeout tells me that the caller stopped waiting. It does not establish whether the remote operation happened.</p><p>The recovery path for our hypothetical payment starts with a stable operation identifier. Every retry of the same authorization uses the same idempotency key and the same payload. The payment integration must honor that contract across concurrent attempts.</p><p>The key belongs to the business action, not the worker process or retry number.</p><p>I also check how long the downstream system retains idempotency records. If recovery outlives that window, blindly resending the request may be unsafe. Reconciliation by business reference, or manual review, becomes necessary.</p><p>Retries need both an attempt limit and a time budget. Here is an illustrative Temporal Java configuration fragment; the durations are hypothetical, and application failures must use the configured non-retryable type names:</p><pre>ActivityOptions paymentOptions = ActivityOptions.newBuilder()<br>    .setStartToCloseTimeout(Duration.ofSeconds(10))<br>    .setScheduleToCloseTimeout(Duration.ofMinutes(2))<br>    .setRetryOptions(RetryOptions.newBuilder()<br>        .setInitialInterval(Duration.ofSeconds(1))<br>        .setBackoffCoefficient(2.0)<br>        .setMaximumInterval(Duration.ofSeconds(20))<br>        .setMaximumAttempts(5)<br>        .setDoNotRetry(&quot;PaymentDeclined&quot;, &quot;AuthorizationDenied&quot;)<br>        .build())<br>    .build();</pre><p>Temporal distinguishes the <a href="https://docs.temporal.io/develop/java/activities/timeouts?utm_source=chatgpt.com">timeout for one Activity attempt from the total Activity time budget</a>. These settings do not cancel an already accepted payment. HTTP client timeouts and downstream idempotency still matter. <a href="https://docs.temporal.io/develop/java/activities/timeouts?utm_source=chatgpt.com">Temporal Documentation</a></p><p>I keep one clearly owned retry policy wherever practical. Three HTTP attempts inside each of five Activity attempts can produce fifteen downstream calls. That is an illustrative upper bound, not a performance measurement.</p><p>A decline needs a business response. A transport failure may justify a retry. An exhausted retry budget with an uncertain payment outcome needs reconciliation.</p><p>Once the outcome is known, compensation depends on business state. Releasing inventory, voiding an authorization, and refunding a captured payment are different operations. Each requires its own durable progress and idempotency protection.</p><p>There is another failure window worth designing explicitly: the forward action may succeed before its completion is recorded. A cleanup plan built only from acknowledged successes can miss that action. Record the intended operation before dispatch, then make reconciliation and compensation able to resolve its outcome.</p><p>A timed-out attempt can still finish. Do not declare cleanup complete until late success is prevented by the downstream operation’s state or handled through reconciliation.</p><p>Microsoft’s <a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/compensating-transaction?utm_source=chatgpt.com">compensating transaction guidance</a> emphasizes that compensation can itself fail and need retries or manual intervention. It also need not restore the original state. <a href="https://learn.microsoft.com/en-us/azure/architecture/patterns/compensating-transaction?utm_source=chatgpt.com">Microsoft Learn</a></p><p>An order already handed to fulfillment may require a cancellation or return process. There is no distributed undo button hiding behind the model.</p><p>Operationally, I track time spent in uncertain states, overdue reservations, retry exhaustion, and failed compensations, all correlated by business operation ID. A successful HTTP response rate will not reveal a checkout abandoned for six hours.</p><h3>5. Human approval must survive both crashes and change</h3><p>“Wait for approval” sounds simple until the workflow waits overnight.</p><p>In our hypothetical checkout, the customer approves a specific product, quantity, currency, maximum total, and destination. I bind that approval to a plan version and an expiry. The approval endpoint authenticates the person, checks their authority, and records a unique decision identifier.</p><p>A chat message saying “looks good” is insufficient unless the system can establish exactly what it authorizes.</p><p>The workflow waits on a durable message or deadline. Temporal’s <a href="https://docs.temporal.io/develop/java/workflows/message-passing?utm_source=chatgpt.com">Signals and Updates</a> provide mechanisms for receiving external decisions; the application supplies the authorization and business validation. <a href="https://docs.temporal.io/develop/java/workflows/message-passing?utm_source=chatgpt.com">docs.temporal.io</a></p><p>Late and duplicate approvals need explicit handling. An approval for plan version two cannot authorize version three. A decision arriving after expiry cannot silently reopen a canceled checkout.</p><p>I prefer waiting for approval before taking scarce inventory whenever the business allows it. After approval, the system must still revalidate price and atomically acquire inventory. If the purchase falls outside the approved terms, it needs another decision.</p><p>For the business deadline, use a durable timer that transitions into cancellation or cleanup. Simply killing the workflow at its deadline can leave effects unresolved. Temporal’s <a href="https://docs.temporal.io/develop/java/workflows/timeouts?utm_source=chatgpt.com">workflow timeout guidance</a> recommends timers when an application needs to take action after a period of time. <a href="https://docs.temporal.io/develop/java/workflows/timeouts?utm_source=chatgpt.com">docs.temporal.io</a></p><p>This machinery has a cost: another service to operate, execution histories to protect, and workflow versions to maintain. I would skip a dedicated engine for a read-only summarizer, a disposable recommendation, or a single operation already made atomic and idempotent by one service.</p><p>For a small process, a database state machine and durable job queue may be enough. The requirement is durable execution semantics, not a particular vendor.</p><p>Tomorrow, kill one agent worker immediately after a downstream side effect succeeds but before its response is recorded, then verify that recovery neither duplicates the action nor abandons it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e2707379c1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Agents Need IAM, Not Just Better Prompts]]></title>
            <link>https://medium.com/@teja230/ai-agents-need-iam-not-just-better-prompts-bf8ef87c6646?source=rss-895cec4be077------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8ef87c6646</guid>
            <dc:creator><![CDATA[Raviteja Kapalavayi]]></dc:creator>
            <pubDate>Fri, 13 Nov 2026 15:01:04 GMT</pubDate>
            <atom:updated>2026-11-13T15:01:04.829Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A Spring Security design for scoped tools, bounded delegation, and production actions you can actually stop.</em></p><p>Imagine a shopping assistant investigating a delayed order. A delivery note tells it to issue a refund, and its shared service credential allows exactly that. The system prompt says “never refund without approval,” but the API has never heard of that rule.</p><p>This is a hypothetical failure. The architectural mistake is concrete: the application gave the model less permission in English than it gave the runtime in credentials.</p><p>My position is simple: an agent should remain contained even when it chooses the wrong tool with convincing arguments. Prompt instructions can improve decisions. They cannot establish who may move money, change an address, or read another customer’s order.</p><p>That authority belongs in systems the model cannot persuade.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UDevZAGS4uAqQGixVyiRg.png" /></figure><h3>Give the task a grant, not a master key</h3><p>I would start with three separate identities: the user requesting work, the application executing it, and the individual task. A shared agent-service credential collapses those distinctions and makes every conversation inherit the same authority.</p><p>For the delayed-order investigation, the initial grant permits reading one order. A refund requires a separate authorization decision, based on authenticated approval or a predefined business policy.</p><p>Consider an illustrative refund grant: one customer, one order, USD 50 total, original payment method only, no further delegation, and a fixed expiration. These are design assumptions, not production measurements.</p><p>The model can propose the action. A trusted authorization workflow creates the grant and binds it to the authenticated user and executing workload. A tool argument claiming approved: true proves nothing.</p><p>Keep the grant in server-controlled storage. Issue a narrow access token containing its identifier, with an audience for the refund API and a scope such as refunds:create. The grant identifier is an application-specific claim, not a magic OAuth feature.</p><p><a href="https://www.rfc-editor.org/rfc/rfc9700.html#section-2.3">OAuth’s security best current practice</a> recommends restricting tokens by audience and by the resources and actions they authorize. An order-reading token should fail at the refund API even when both services trust the same issuer. <a href="https://www.rfc-editor.org/rfc/rfc9700.html?utm_source=chatgpt.com">rfc-editor.org</a></p><p>Where supported, <a href="https://www.rfc-editor.org/rfc/rfc8693.html#section-4.1">OAuth Token Exchange</a> can preserve both the subject and the current actor through the sub and act claims. The authorization server must establish those identities; the model must not supply trusted identity claims. <a href="https://www.rfc-editor.org/rfc/rfc8693.html?utm_source=chatgpt.com">rfc-editor.org</a></p><p>My issuance rule is an intersection: user entitlement, workload permission, task grant, and current policy. Token exchange does not enforce that rule automatically. Configure it, reject privilege expansion, and prevent child tasks from extending the parent’s deadline or acquiring broader authority.</p><p>For unattended work, use an explicitly authorized workload grant. Do not invent a human user to make the audit log look reassuring.</p><h3>Make every tool cross an authorization boundary</h3><p>I prefer business tools such as readOrder and requestRefund over a generic callApi(url, method, body) tool carrying broad credentials.</p><p>A trusted executor maps each registered tool to a fixed destination, operation, input schema, and required permission. It obtains the appropriate token and attaches it outside the model context. Credentials never need to appear in a prompt or tool response.</p><p>The executor checks permission, but the destination API checks it again. Hiding a tool from the model is useful interface design; it does not protect an endpoint reachable through another path.</p><p>For a Java 17 application using Spring Boot 3.5 and Spring Security 6.5, this partial configuration illustrates the request boundary for a dedicated refund service. Imports and application wiring are omitted.</p><pre>@Bean<br>SecurityFilterChain refundApi(HttpSecurity http) throws Exception {<br>    return http<br>        .csrf(csrf -&gt; csrf.disable())<br>        .sessionManagement(session -&gt; session<br>            .sessionCreationPolicy(SessionCreationPolicy.STATELESS))<br>        .authorizeHttpRequests(auth -&gt; auth<br>            .requestMatchers(HttpMethod.POST, &quot;/refunds&quot;)<br>                .hasAuthority(&quot;SCOPE_refunds:create&quot;)<br>            .anyRequest().denyAll())<br>        .oauth2ResourceServer(oauth -&gt; oauth<br>            .jwt(Customizer.withDefaults()))<br>        .build();<br>}</pre><p>This assumes machine-to-machine HTTPS requests authenticated only through explicit bearer headers, with no cookie or browser-managed authentication. That assumption justifies disabling CSRF here; <a href="https://docs.spring.io/spring-security/reference/features/exploits/csrf.html#csrf-and-stateless-browser-applications">statelessness alone does not</a>. <a href="https://docs.spring.io/spring-security/reference/features/exploits/csrf.html?utm_source=chatgpt.com">docs.spring.io</a></p><p>With the OAuth resource-server starter and Boot’s default decoder configuration, configure both issuer and audience. These example domains represent the hypothetical deployment:</p><pre>spring:<br>  security:<br>    oauth2:<br>      resourceserver:<br>        jwt:<br>          issuer-uri: https://identity.example.com<br>          audiences: https://refunds.example.com</pre><p><a href="https://docs.spring.io/spring-security/reference/6.5/servlet/oauth2/resource-server/jwt.html?utm_source=chatgpt.com">Spring Security’s resource-server documentation</a> explains signature, issuer, and timestamp validation, audience configuration, and the default SCOPE_ authority mapping. If you replace the decoder, preserve those checks explicitly. <a href="https://docs.spring.io/spring-security/reference/6.5/servlet/oauth2/resource-server/jwt.html?utm_source=chatgpt.com">docs.spring.io</a></p><p>This configuration admits a request with the right scope. It does not validate the application’s delegation record, tenant, order ownership, amount, or payment destination. Those checks belong in the service handling the action, before it accepts a refund intent.</p><p>Derive the tenant from trusted authentication and grant data, then query the order within that tenant. A caller-supplied order ID is a lookup key, not evidence of ownership.</p><h3>A scope cannot enforce a refund budget</h3><p>Suppose the grant permits USD 50 total. Two concurrent requests each ask for USD 40. Both possess valid tokens, both have the right scope, and both pass a check against an unchanged USD 50 balance.</p><p>The result is USD 80 of accepted refunds. Better prompts will not repair this race.</p><p>I treat authorization for a state-changing action as part of the transaction accepting that action. In the refund service’s database, lock or conditionally update the authoritative grant and order records, verify that the grant remains active, check ownership and eligibility, and reserve the amount atomically.</p><p>Represent this example’s USD amounts in integer cents. The reservation must satisfy both the grant’s remaining allowance and the order’s remaining refundable amount, including pending reservations.</p><p>In that same transaction, persist the refund intent, its authorization decision, and an outbox record. A worker can then call the payment provider without holding a database transaction open across the network.</p><p>Retries reuse the persisted refund intent and a stable provider idempotency key. At the API boundary, scope idempotency keys to the caller and grant, bind them to a request hash, and reject reuse with different parameters. Choosing a new key must not reset the grant’s budget.</p><p>If the provider times out, retain the reservation while reconciling the outcome. Releasing it immediately can fund a second refund while the first one quietly succeeds. If the provider cannot support safe deduplication or status reconciliation, automatic retries need a more conservative workflow.</p><p>This is the less obvious consequence of agent authorization: permissions that can be consumed require durable accounting. A scope answers whether a type of operation is allowed. It cannot tell you how much authority concurrent requests have already spent.</p><p>For an action requiring human approval, bind approval to the exact order, amount, currency, destination, and expiry. If those parameters change, obtain a new approval. The server should construct the confirmation from validated data, rather than trust the agent’s summary.</p><h3>Short-lived tokens need a real stop button</h3><p>For this example, assume five-minute access tokens and a fifteen-minute task deadline. Those durations illustrate separate controls; they are not universal recommendations.</p><p>Keep renewal credentials outside the model’s reach. The trusted executor may obtain another access token only while the task grant remains active, and no token may outlive the task deadline. Otherwise, a five-minute token with unlimited renewal is a permanent credential wearing a wristwatch.</p><p>There is a subtle limitation in <a href="https://www.rfc-editor.org/rfc/rfc8693.html#section-2.1">RFC 8693’s exchange semantics</a>: exchanging a token does not inherently invalidate the input token or create automatic revocation propagation between parent and child tokens. <a href="https://www.rfc-editor.org/rfc/rfc8693.html?utm_source=chatgpt.com">rfc-editor.org</a></p><p>Logging a user out therefore does not prove every delegated token has stopped working.</p><p>For refund acceptance, I require a check against authoritative grant state inside the transaction. Revocation and acceptance must serialize against that state. A refund accepted before revocation may still complete; stopping already accepted work requires a separate cancellation policy.</p><p>An offline JWT signature check cannot discover a newly revoked grant. Introspection or application-level grant checks can provide fresher decisions, but their caches define the remaining delay. Choose that delay deliberately.</p><p>I would fail closed on new refund acceptance if authoritative grant state is unavailable. That costs availability. It also makes the stop button mean something.</p><p>Sender-constrained tokens can reduce credential theft risk. <a href="https://www.rfc-editor.org/rfc/rfc9449.html?utm_source=chatgpt.com">DPoP</a> requires proof of possession of the associated key, rather than accepting the token alone. It cannot prevent a misled agent from asking its legitimate executor to perform an otherwise permitted action. Authorization boundaries still matter. <a href="https://www.rfc-editor.org/rfc/rfc9449.html?utm_source=chatgpt.com">rfc-editor.org</a></p><h3>Audit decisions, then test the boundary</h3><p>A conversation transcript explains what the agent said. An authorization trail must explain why the system allowed the effect.</p><p>For each attempt, record the trusted subject and actor, task and grant IDs, tool, target resource, policy version, decision, reason code, and correlation ID. For accepted mutations, connect that decision to the durable intent and eventual provider outcome.</p><p>Record denials too. Repeated attempts to cross tenants, switch destinations, or increase amounts are useful signals even when every request fails. Keep raw credentials and unnecessary customer content out of logs.</p><p>For refunds, the transactionally stored decision and outbox provide durable evidence even if the central logging pipeline is down. Restrict modification of those records and export them to an audit destination with controlled retention. Ordinary application logs should not be the only evidence that money was authorized to move.</p><p>Then test the boundary without involving the model: a valid token for the wrong audience, another customer’s order, an expired grant, concurrent budget consumption, and a retry with changed parameters. The expected outcome is rejection by the service, regardless of how persuasive the request sounds.</p><p>This design is intentionally heavier than a public catalog assistant needs. Public, read-only tools may need rate limits and cost controls without user delegation or a transactional grant ledger. Private reads still require tenant and object authorization.</p><p>Nor does IAM prove that every permitted action reflects the user’s intent. A compromised workflow can misuse an overly broad grant. Keep prompts, input isolation, and approvals where they help, while ensuring the API enforces their consequences.</p><p>Tomorrow, take one production agent tool and write an integration test proving that a valid credential cannot perform one action outside its task’s authority.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8ef87c6646" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI Shopping Will Break Your Promotion Engine]]></title>
            <link>https://medium.com/@teja230/ai-shopping-will-break-your-promotion-engine-1006bd4aa6da?source=rss-895cec4be077------2</link>
            <guid isPermaLink="false">https://medium.com/p/1006bd4aa6da</guid>
            <dc:creator><![CDATA[Raviteja Kapalavayi]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 15:01:05 GMT</pubDate>
            <atom:updated>2026-11-11T15:01:05.982Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Make discounts independent of cart history, and enforce redemption where concurrent requests meet.</em></p><p>Imagine a hypothetical checkout where a $120 cart qualifies for $20 off purchases of $100 or more. A shopper removes a $30 item, but the discount survives. The remaining $90 of merchandise now costs $70, before tax and shipping.</p><p>An agent asked to find the lowest price could discover that sequence, preserve it, and repeat it across eligible shopping sessions. It does not need to understand your promotion engine. It only needs to notice that one sequence produces a lower total.</p><p>My claim is that making pricing independent of request order matters more than recognizing whether the shopper is an AI agent.</p><p>Rate limits can reduce exploration. They cannot make an invalid discount valid. I want a checkout whose pricing rules remain correct even when the caller is unusually persistent, highly organized, and completely uninterested in the intended user journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GiIuVFJBU_Mh8Hbk9pbtZg.png" /></figure><h3>1. Stop letting request order choose the discount</h3><p>The first failure mode is treating cart mutations as adjustments to an already-discounted total.</p><p>“Apply coupon” subtracts money. “Remove item” subtracts the item’s price. “Change delivery” updates shipping. Each handler looks reasonable in isolation, while nobody owns the validity of the final combination.</p><p>For the opening example, removing the item must trigger a fresh eligibility decision. If the rule requires $100 of eligible merchandise before this coupon, a $90 cart fails that rule regardless of how it got there.</p><p>Stacking has the same problem. In a hypothetical $100 cart, applying 20% off and then $10 off produces $70. Reversing those operations produces $72. Both calculations are internally consistent; the business must choose the permitted order.</p><p>My default is explicit calculation stages, compatibility rules, and stable priorities. A campaign also needs a precise threshold basis: merchandise before discounts, after item discounts, or some other declared subtotal. “Minimum spend” is not a sufficiently detailed specification.</p><p>Be careful with apparently obvious configuration names. The <a href="https://docs.commercetools.com/api/pricing-and-discounts-overview#between-multiple-cart-discounts">commercetools discount documentation</a> explains that total-price discounts apply after other discount targets and can ignore their stop-stacking behavior. A stop flag does not necessarily mean “nothing else can discount this cart.” <a href="https://docs.commercetools.com/api/pricing-and-discounts-overview?utm_source=chatgpt.com">API</a></p><p>I also separate deterministic selection from maximum savings. A priority-based engine can consistently choose a result that is not the cheapest permitted combination. That is acceptable if it matches the product promise. If you promise the best available deal, the server must evaluate the permitted combinations with stable tie-breaking; arrival order cannot be the optimizer.</p><p>Agents should compete to find good offers, not discover which API handler forgot to remove one.</p><h3>2. Calculate from facts, not yesterday’s total</h3><p>I would put a pure pricing evaluator behind the Spring Boot application layer. It receives a complete input snapshot and returns amounts, allocations, and rule decisions. It does not fetch changing prices, query customer history, or read the wall clock halfway through evaluation.</p><p>That snapshot includes normalized merchandise, currency, price versions, promotion versions, authoritative customer eligibility, requested coupons, fulfillment context, and an explicit evaluation time. Include tax and shipping inputs when they affect eligibility or the quoted total.</p><p>“Same cart, same price” is shorthand. The useful guarantee is <strong>same complete pricing inputs, same pricing result</strong>.</p><p>A coupon string is a request to evaluate an offer, not proof that the shopper qualifies. Derive account identity from authenticated authorization, including the customer’s delegated authority when an agent acts for them. Load membership and audience eligibility from trusted sources. A client-supplied firstOrder=true should have precisely zero persuasive power.</p><p>Recalculate from base prices and those inputs. Never feed yesterday’s discounted total back into today’s evaluator.</p><p>Canonicalization matters beyond sorting coupon codes. Suppose three identical units each cost $0.05 and receive 10% off. With half-up rounding, rounding each unit’s discount produces $0.03 of savings; rounding the aggregate discount produces $0.02. Those are illustrative calculations, not production measurements.</p><p>Define the rounding boundary, currency precision, and discount allocation policy. Equivalent line splitting should not change the result unless the commercial rules intentionally distinguish those lines. Preserve meaningful differences such as seller or fulfillment terms when normalizing.</p><p>Store allocations with the order, too. Refunds should follow an explicit policy using the purchased amounts, rather than silently rerunning today’s promotions against last month’s order.</p><p>Versioning makes this explainable. Retain the actual input snapshots, immutable rule definitions, and evaluator version; version labels alone cannot reproduce a decision after their underlying data disappears.</p><h3>3. Decide what a quote actually promises</h3><p>Deterministic pricing does not mean prices never change. It means changes happen through an explicit contract.</p><p>Suppose a hypothetical quote uses a $100 base price and a $20 promotion. Before checkout, the base price becomes $90 and the promotion ends. Keeping the old discount while refreshing only the base price creates a $70 combination that neither pricing snapshot authorized.</p><p>Choose a policy: honor a defined snapshot until expiry, or reprice before purchase and require acceptance when the payable amount changes. A quote ID without that policy is just a reference to an argument you will have later.</p><p>My default for ordinary retail is a short-lived quote bound to the customer, cart version, currency, fulfillment selection, and pricing snapshot. Checkout either accepts that exact quote under its stated conditions or returns a replacement. The customer or delegated agent must accept the new amount within its purchasing authority.</p><p>The cart version must be checked atomically when creating the pending order. Checking it and then allowing another cart update before order creation reintroduces the race through a different door.</p><p>There is another distinction: a price quote need not reserve a limited coupon or campaign budget. If availability remains conditional until checkout, say so. If the quote guarantees that benefit, reserve it when issuing the guarantee.</p><p>Reservations create their own operational cost. Idle carts can occupy scarce benefits. Bound reservation lifetimes and outstanding reservations per customer; do not let repeated quote requests accumulate claims indefinitely.</p><p>For rapidly changing prices or scarce inventory, honoring snapshots may be inappropriate. Repricing can be the right policy. Mixing snapshots accidentally is not a policy.</p><h3>4. Enforce redemption where requests compete</h3><p>A perfectly deterministic evaluator can approve two simultaneous checkouts for the same one-use coupon.</p><p>Both requests read “unused.” Both calculate correctly. Both proceed. No amount of careful arithmetic fixes that race.</p><p>I separate eligibility evaluation from acquiring the right to redeem. For a hypothetical single-store system allowing one redemption per campaign per customer, this partial PostgreSQL schema illustrates the boundary; foreign keys and audit columns are omitted:</p><pre>CREATE TABLE promotion_claim (<br>    campaign_id UUID NOT NULL,<br>    customer_id UUID NOT NULL,<br>    order_id UUID NOT NULL,<br>    state TEXT NOT NULL CHECK (<br>        state IN (&#39;RESERVED&#39;, &#39;REDEEMED&#39;, &#39;RELEASED&#39;)<br>    ),<br>    PRIMARY KEY (campaign_id, order_id)<br>);</pre><pre>CREATE UNIQUE INDEX one_live_claim_per_customer<br>    ON promotion_claim (campaign_id, customer_id)<br>    WHERE state IN (&#39;RESERVED&#39;, &#39;REDEEMED&#39;);</pre><p>PostgreSQL supports <a href="https://www.postgresql.org/docs/current/indexes-partial.html?utm_source=chatgpt.com">unique partial indexes</a> for enforcing uniqueness over a selected subset of rows. Here, an outstanding reservation or completed redemption blocks another live claim for that customer and campaign. <a href="https://www.postgresql.org/docs/current/ddl-constraints.html?utm_source=chatgpt.com">postgresql.org</a></p><p>In this design, the Spring Boot service creates the pending order, claim, and payment-work outbox record in one local database transaction. It also atomically validates the cart version and any shared campaign capacity. A uniqueness conflict rejects the competing checkout; campaign-budget exhaustion rolls back the entire transaction.</p><p>Do not confuse that with a preliminary SELECT followed by an unchecked write. PostgreSQL&#39;s <a href="https://www.postgresql.org/docs/current/transaction-iso.html#XACT-READ-COMMITTED">Read Committed behavior</a> permits successive queries to observe different committed state. Use the constraint for customer uniqueness and a locked or conditional update for shared capacity; the two protect different invariants. <a href="https://www.postgresql.org/docs/current/transaction-iso.html?utm_source=chatgpt.com">postgresql.org</a></p><p>Payment happens outside that transaction. An outbox worker retries the same durable payment attempt, then advances the order and claim through guarded state transitions. A timeout leaves the payment outcome uncertain. Reconcile it before releasing the claim; otherwise a late success can overlap a second redemption.</p><p>Idempotency is another separate boundary. <a href="https://docs.stripe.com/api/idempotent_requests?utm_source=chatgpt.com">Stripe’s API v1 idempotency contract</a> reuses a stored response for the same key and rejects changed parameters. Your checkout should likewise bind a key to the authenticated customer and request payload. But two different keys still require the business uniqueness rule. <a href="https://docs.stripe.com/api/idempotent_requests?utm_source=chatgpt.com">docs.stripe.com</a></p><p>Finally, “one per customer account” does not mean “one per human.” Account farming requires additional abuse controls. Deterministic pricing cannot solve identity by itself.</p><h3>5. Test the routes to the cart</h3><p>A test saying “coupon applies to a qualifying cart” will not catch the opening bug. The failure lives in the sequence that follows.</p><p>I want generated mutation sequences that add and remove items, apply coupons in different orders, switch fulfillment, merge guest carts, and retry checkout. Hold the pricing snapshot and evaluation time fixed when comparing equivalent final states.</p><p>The properties worth checking are specific:</p><ul><li>Equivalent final pricing inputs produce identical amounts and allocations, regardless of mutation history.</li><li>Recalculating an unchanged snapshot does not apply a discount again.</li><li>Removing qualifying merchandise removes the associated benefit when the rule requires it.</li><li>Concurrent checkouts cannot exceed customer redemption limits or shared campaign capacity.</li><li>A payment retry cannot create a second purchase or silently use a different quote.</li></ul><p>Avoid attractive but false properties. “Adding an item can never reduce the total” fails for legitimate threshold promotions. Your tests need to encode the commercial contract, including its intentional discontinuities.</p><p>For operations, retain a restricted decision trace: snapshot identity, applied and rejected rules, rejection reasons, allocations, and claim transitions. Monitor quote-to-order price changes and redemption conflicts by campaign. Put individual cart identifiers in traces rather than high-cardinality metric labels.</p><p>None of this requires every store to build a general promotion solver. One non-stackable discount can use a much simpler implementation. A deliberately history-dependent benefit can also be valid, provided its earned entitlement becomes explicit, trusted state.</p><p>Tomorrow, take your highest-value promotion and add one regression test that reaches the same final cart through two different mutation sequences, then compares the complete pricing result.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1006bd4aa6da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When AI Agents Become Your Customers]]></title>
            <link>https://medium.com/@teja230/when-ai-agents-become-your-customers-832400d17fc9?source=rss-895cec4be077------2</link>
            <guid isPermaLink="false">https://medium.com/p/832400d17fc9</guid>
            <dc:creator><![CDATA[Raviteja Kapalavayi]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 15:01:03 GMT</pubDate>
            <atom:updated>2026-11-09T15:01:03.354Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A hypothetical Spring Boot checkout that makes delegated spending, prices, inventory, and retries enforceable.</em></p><p>Imagine a shopper authorizes an agent to buy one pair of shoes for at most $150, including shipping and tax. The agent submits checkout, times out, and tries again with a fresh request ID. Both requests succeed.</p><p>Every API call might be authenticated. Every price might be correct. The customer still gets two pairs.</p><p>My argument: <strong>an autonomous checkout should consume a durable purchase authorization as part of the order transaction.</strong> Human checkout needs strong controls too. Agents make the gaps harder to ignore because they can explore alternatives and retry without the hesitation our interfaces quietly depend on.</p><p>Consider a hypothetical Spring Boot store selling physical goods. I’d keep purchase authorizations, quotes, coupon entitlements, inventory reservations, and orders in PostgreSQL initially. Redis serves cached availability and rate limits. An outbox feeds payment workers and Kafka consumers.</p><p>That arrangement keeps the critical local decisions transactional. Payment remains an external operation with an explicit recovery path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0sRFaKaI-pZwS2xIiqJHA.png" /></figure><h3>1. Give the agent a spending boundary</h3><p>A token identifying an agent answers who is calling. It does not, by itself, establish what this customer allowed that agent to buy.</p><p>For the shoe purchase, I want an authorization issued through a trusted consent flow, bound to the customer, agent client, merchant, permitted items, quantity, currency, delivery destination, and maximum total. It also needs an expiration, revocation state, and a stable purchase ID.</p><p>The agent can present that authorization. It cannot create broader authority by putting “the customer approved” in a request body.</p><p><a href="https://www.rfc-editor.org/rfc/rfc9396.html?utm_source=chatgpt.com">OAuth Rich Authorization Requests</a> provides a standard way to express detailed permissions, including payment amounts and recipients. That is useful vocabulary; the merchant still has to enforce the approved constraints. <a href="https://www.rfc-editor.org/rfc/rfc9396.html?utm_source=chatgpt.com">rfc-editor.org</a></p><p>I separate permission to search from permission to commit. An agent may compare ten products while holding authority to buy exactly one. Changing the recipient, adding a subscription, or exceeding the approved total requires a new decision through the consent flow.</p><p>The less obvious problem is concurrency. Suppose a reusable grant allows $150 in total spending. Two simultaneous $90 orders each pass a naive “amount below limit” check. Together, they spend $180.</p><p>For reusable grants, I reserve spending capacity in a shared ledger before initiating payment. For this single-purchase example, I allow one order against the approved purchase ID.</p><p>Authorization therefore becomes state that checkout consumes. A valid signature cannot tell me whether another request already used the permission.</p><h3>2. Commit an exact quote</h3><p>An agent might discover a price in a search result, a product description, or an earlier API response. None of those should determine what checkout charges.</p><p>I expose a quote operation that calculates the complete purchase on the server. The stored quote binds item variants, quantities, discounts, shipping, tax, currency, destination, and expiration to the customer and purchase authorization.</p><p>The commit request references that quote. It does not submit an authoritative total.</p><p>Suppose the agent finds shoes advertised at $120, but the delivered total is $154. A $150 authorization must reject that purchase. Checking only the merchandise subtotal defeats the spending boundary.</p><p>I also distinguish a maximum budget from acceptance of a particular quote. A customer might approve a $142 purchase under a $150 ceiling. That does not automatically authorize a later $149 quote. The grant must explicitly permit repricing; otherwise, material changes need renewed approval.</p><p>For this design, I honor a stored quote until its expiration, subject to stated availability conditions. Once it expires, checkout returns a new quote instead of silently recalculating and charging.</p><p>Coupons belong inside this same boundary. Consider a single-use $20 promotion: two parallel quotes can both look eligible before either purchase commits. Reserving the entitlement during checkout prevents both orders from spending it.</p><p>I enforce stacking rules and eligibility on the server, with a database constraint for the intended entitlement, such as one redemption per customer and campaign. A canceled purchase releases its reservation according to campaign policy.</p><p>Rate limits help contain coupon enumeration, but an IP address is a poor substitute for a customer entitlement. One agent provider can serve many legitimate shoppers, while one shopper can use several agents.</p><p>The operational signal I want is failed promotion attempts per customer and agent client, alongside campaign redemption patterns. Raw request volume alone tells an incomplete story.</p><h3>3. Reserve only when the agent commits</h3><p>Exploration should not remove stock from sale.</p><p>As an illustrative example, 40 agents each comparing five variants could create 200 holds without producing a single order. If every comparison reserves inventory, the catalog can appear sold out while the warehouse is full.</p><p>I let quotes report availability without guaranteeing it. The purchase operation creates a short reservation, bounded by a deadline and limits on outstanding holds per customer.</p><p>Here is an illustrative Java 17+ service method inside the Spring Boot application. Repository implementations and validation details are omitted; this shows the transaction boundary:</p><pre>@Transactional<br>public UUID accept(<br>        AuthenticatedActor actor,<br>        PurchaseCommand command) {<br>    var purchase = purchases.lockOwned(<br>            command.purchaseId(), actor.customerId());<br>    purchase.requireAgent(actor.clientId());</pre><pre>    if (purchase.orderId() != null) {<br>        purchase.requireSameQuote(command.quoteId());<br>        return purchase.orderId();<br>    }</pre><pre>    var quote = quotes.requireUsable(<br>            command.quoteId(), purchase);<br>    purchase.requireAuthorized(quote);</pre><pre>    promotions.reserveEntitlements(purchase, quote);<br>    inventory.reserveAll(purchase, quote);<br>    var order = orders.createPending(purchase, quote);</pre><pre>    purchase.bindOrder(order.id(), quote.id());<br>    outbox.appendPaymentRequested(order);<br>    return order.id();<br>}</pre><p>The authenticated actor comes from verified security context. The purchase row lock serializes competing commits, including authorization revocation through the same row. Authorization checks include expiry, destination, items, currency, and total.</p><p>Every repository write uses the same PostgreSQL transaction. A reservation failure raises an exception configured to roll back everything. The method must run through <a href="https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/annotations.html?utm_source=chatgpt.com">Spring’s transaction proxy</a>; calling it from another method on the same instance does not activate that proxy behavior. <a href="https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/annotations.html?utm_source=chatgpt.com">docs.spring.io</a></p><p>Inventory reservation still needs its own concurrency protection. I use conditional updates that decrement available quantity only when sufficient stock remains, then require the expected affected-row count. PostgreSQL’s <a href="https://www.postgresql.org/docs/current/transaction-iso.html?utm_source=chatgpt.com">Read Committed behavior</a> rechecks an update’s condition after a concurrent updater commits. A preceding ordinary read is insufficient. <a href="https://www.postgresql.org/docs/current/transaction-iso.html?utm_source=chatgpt.com">postgresql.org</a></p><p>Multi-item reservations lock stock rows in a consistent order. Deadlocks can still require bounded transaction retries using the same purchase ID.</p><p>The transaction also creates the durable outbox event. No payment network call runs while these database locks are held.</p><h3>4. Make purchase identity survive retries</h3><p>An idempotency key protects against a repeated request only when the caller reuses it.</p><p>An agent that interprets a timeout as “start over” may generate a new key. Your endpoint can correctly honor both keys while incorrectly buying twice.</p><p>I keep two layers of protection.</p><p>The HTTP layer stores a key scoped to the customer and operation, a fingerprint of the validated command, and the resulting order reference. Reusing a key with different input returns a conflict.</p><p>The business layer enforces a unique order per approved purchase ID. That ID originates in the authorization flow and survives agent restarts, transport retries, and new HTTP keys. A different quote against an already committed purchase also returns a conflict.</p><p>This does not mean deduplicating identical baskets. A customer can legitimately buy the same shoes twice. The second purchase needs distinct authority.</p><p>Before initiating payment, the worker rechecks the order’s eligibility and reservation deadline. It uses a durable payment-operation ID as its provider idempotency key and stores the provider’s payment reference. A timeout leaves the operation unresolved; it does not authorize another payment attempt with a new identity.</p><p>Provider retention matters. <a href="https://docs.stripe.com/api/idempotent_requests?utm_source=chatgpt.com">Stripe’s API v1 documentation</a> says idempotency keys may be removed once they are at least 24 hours old. Reusing a pruned key can execute a new request. <a href="https://docs.stripe.com/api/idempotent_requests?utm_source=chatgpt.com">docs.stripe.com</a></p><p>Consequently, a long-delayed retry must reconcile the existing provider operation first. If its outcome cannot be established, I keep it unresolved for investigation instead of blindly issuing another charge.</p><h3>5. Treat payment confirmation as a separate decision</h3><p>An accepted checkout request should return an order reference and an honest state such as PAYMENT_PENDING. It should not claim that the purchase is complete.</p><p>Payment can require customer action, remain in processing, or be authorized without capture. <a href="https://docs.stripe.com/payments/paymentintents/lifecycle?utm_source=chatgpt.com">Stripe’s payment lifecycle</a> explicitly distinguishes those outcomes. An agent’s purchase permission does not eliminate payment authentication requirements. <a href="https://docs.stripe.com/payments/paymentintents/lifecycle?utm_source=chatgpt.com">docs.stripe.com</a></p><p>For this hypothetical store, fulfillment requires a verified successful payment and a valid inventory allocation. An agent-reported success or a browser redirect cannot satisfy that condition.</p><p>The webhook endpoint verifies the provider signature over the original request body and durably records the event before acknowledging it. A worker matches the payment to the expected merchant account, order, amount, and currency.</p><p><a href="https://docs.stripe.com/webhooks?utm_source=chatgpt.com">Stripe documents duplicate and unordered webhook delivery</a>. I deduplicate events and guard business state transitions, so two different notifications cannot trigger two shipments. When an event conflicts with local state, the worker retrieves the provider’s current payment state. A reconciliation job also revisits payments left unresolved by missing notifications. <a href="https://docs.stripe.com/webhooks?utm_source=chatgpt.com">docs.stripe.com</a></p><p>The nastiest race is between payment success and reservation expiry.</p><p>Suppose a hold expires at 12:05, stock is released, and payment success arrives at 12:06. The payment is real. The stock guarantee is gone.</p><p>I serialize expiry and confirmation against the same order and reservation records. If expiry wins, late success enters an exception path: attempt a fresh allocation, then refund if allocation fails. It never silently releases fulfillment.</p><p>An expired stock hold also does not prove that payment failed. I retain the purchase’s payment exposure until reconciliation establishes the outcome, rather than restoring spending capacity while a charge might still succeed.</p><p>This creates operational work worth measuring: unresolved payment age, expired holds awaiting payment resolution, late-payment allocation failures, and pending refunds. I retain authorization and quote references for investigation without logging bearer tokens or payment secrets.</p><p>The trade-off is real. This design adds durable state and contention, particularly around popular inventory and shared budgets. If inventory lives in another service, the local transaction cannot reserve it atomically; use durable orchestration with idempotent reservation commands and compensating releases.</p><p>An agent that only recommends products and hands the final purchase to a human does not need this entire delegated-spending mechanism. Low-risk digital goods may not need stock holds. Slow payment methods need an explicit allocation policy instead of an arbitrarily long reservation.</p><p>Tomorrow, send two concurrent checkout requests with different idempotency keys but the same approved purchase ID, and verify that they produce one order and one payment operation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=832400d17fc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Contract Testing Without Slowing Delivery]]></title>
            <link>https://medium.com/@teja230/contract-testing-without-slowing-delivery-d16c27fb41ce?source=rss-895cec4be077------2</link>
            <guid isPermaLink="false">https://medium.com/p/d16c27fb41ce</guid>
            <dc:creator><![CDATA[Raviteja Kapalavayi]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 15:31:01 GMT</pubDate>
            <atom:updated>2026-11-02T15:31:01.875Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical Pact workflow for testing client assumptions, verifying providers, and checking compatibility before deployment.</em></p><p>Imagine a pricing service renames totalMinor to amountMinor. The latest checkout code already understands the change, both teams have green builds, and production breaks because an older checkout version is still serving traffic.</p><p>That is a hypothetical failure, but it exposes a real weakness: compatibility depends on the versions running together.</p><p>I want contract testing to make independent releases easier. That requires more than generating a JSON file and adding another CI job.</p><p>My position is simple: <strong>contract testing earns its place when it can block an incompatible deployment while allowing unrelated work to continue.</strong> The tests, version metadata, and deployment checks all have to support that outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bv5hse-Oz7EC8EcTEjCRyg.png" /></figure><h3>1. Start with the client code that can break</h3><p>For a checkout-to-pricing integration, I start with the assumptions inside the checkout client.</p><p>Does it require an integer amount? Does it distinguish an expired quote from a missing one? Does it expect a particular error code before asking the customer to review a changed price?</p><p>In <a href="https://docs.pact.io/getting_started/how_pact_works?utm_source=chatgpt.com">Pact’s consumer-driven workflow</a>, the consumer exercises its code against a mock provider. The resulting contract records the expected interactions. Provider verification then sends those requests to the provider and checks its responses against the contract. <a href="https://docs.pact.io/getting_started/how_pact_works?utm_source=chatgpt.com">Pact Docs</a></p><p>The consumer test needs to call the application’s actual HTTP adapter. That puts request construction, serialization, response parsing, and error mapping inside the test.</p><p>Here is a partial Java/JUnit example for our hypothetical integration. PricingClient represents the application’s real adapter, with a configurable base URL. Imports and its implementation are omitted.</p><pre>@PactConsumerTest<br>class PricingContractTest {<br>    @Pact(provider = &quot;pricing-service&quot;, consumer = &quot;checkout-service&quot;)<br>    public RequestResponsePact quote(PactDslWithProvider builder) {<br>        return builder<br>            .given(&quot;quote q-123 exists in USD&quot;)<br>            .uponReceiving(&quot;a request for an existing quote&quot;)<br>            .method(&quot;GET&quot;)<br>            .path(&quot;/quotes/q-123&quot;)<br>            .willRespondWith()<br>            .status(200)<br>            .headers(Map.of(&quot;Content-Type&quot;, &quot;application/json&quot;))<br>            .body(new PactDslJsonBody()<br>                .stringValue(&quot;quoteId&quot;, &quot;q-123&quot;)<br>                .integerType(&quot;totalMinor&quot;, 1499)<br>                .stringValue(&quot;currency&quot;, &quot;USD&quot;))<br>            .toPact();<br>    }</pre><pre>    @Test<br>    @PactTestFor(pactMethod = &quot;quote&quot;)<br>    void readsQuote(MockServer server) {<br>        var client = new PricingClient(server.getUrl());<br>        var quote = client.getQuote(&quot;q-123&quot;);<br>        assertEquals(1499L, quote.totalMinor());<br>        assertEquals(&quot;USD&quot;, quote.currency());<br>    }<br>}</pre><p>This follows Pact’s <a href="https://docs.pact.io/implementation_guides/jvm/consumer/junit5?utm_source=chatgpt.com">JUnit 5 consumer pattern</a>. The test connects the declared interaction to the client code that depends on it. <a href="https://docs.pact.io/implementation_guides/jvm/consumer/junit5?utm_source=chatgpt.com">Pact Docs</a></p><p>The matcher choices matter. With Pact’s <a href="https://docs.pact.io/implementation_guides/jvm/consumer?utm_source=chatgpt.com">Java DSL</a>, integerType checks the provider’s value is an integer; 1499 supplies the example returned by the mock server. The consumer assertion checks that its adapter reads that example correctly. It does <strong>not</strong> require the provider to calculate exactly 1499 during verification. <a href="https://docs.pact.io/implementation_guides/jvm/consumer?utm_source=chatgpt.com">Pact Docs</a></p><p>That distinction prevents accidental overconfidence. A provider returning cents where the client expects another unit can still satisfy an integer matcher. Units need an explicit agreement and appropriate semantic tests.</p><p>I also include the error responses that change consumer behavior. If checkout handles an expired quote differently from a missing quote, both interactions deserve coverage. A success-only contract protects a surprisingly small part of checkout.</p><h3>2. Make provider verification exercise the real boundary</h3><p>A contract that verifies against a fake controller gives me little confidence in the controller I will deploy.</p><p>For a Spring Boot provider, my default is to start the application on a random port and verify through HTTP. That exercises routing, request binding, response serialization, and exception handling together. I keep downstream dependencies controlled so a pricing contract does not require an entire commerce platform to be available.</p><p>The provider owns the setup behind given(&quot;quote q-123 exists in USD&quot;).</p><p>That state might insert a stored quote into an isolated database or configure a downstream dependency. Pact’s <a href="https://docs.pact.io/getting_started/provider_states?utm_source=chatgpt.com">provider-state mechanism</a> exists to establish these preconditions, and each interaction should run independently. <a href="https://docs.pact.io/getting_started/provider_states?utm_source=chatgpt.com">Pact Docs</a></p><p>I make database fixtures committed before the HTTP request and isolate data between parallel verification workers. A test should not pass because another interaction happened to create its quote first.</p><p>Fixture design can also hide broken request handling.</p><p>Suppose an endpoint should filter quotes by customer. If the fixture contains only one customer, a provider that ignores the filter may still return the expected result. Pact’s documentation describes this exact class of <a href="https://docs.pact.io/provider/using_provider_states_effectively?utm_source=chatgpt.com">false positive from insufficient provider-state data</a>. <a href="https://docs.pact.io/provider/using_provider_states_effectively?utm_source=chatgpt.com">Pact Docs</a></p><p>My response is to include a competing record and assert the relevant result precisely enough to expose the mistake. A permissive “at least one result” matcher would undermine that setup.</p><p>For authenticated endpoints, I use test credentials and preserve the authorization behavior under test. Production tokens never belong in published contracts. If verification bypasses the security layer, I treat authorization as a separate coverage obligation.</p><h3>3. Make CI answer a deployment question</h3><p>A passing provider test answers a narrow question: this provider version satisfies these selected contracts.</p><p>The deployment question is broader: can this candidate run with the versions currently present in the target environment?</p><p>I wire the workflow in four steps:</p><ol><li><strong>Consumer CI:</strong> Run the consumer tests and publish successful contracts with an immutable application version and branch.</li><li><strong>Provider CI:</strong> Retrieve the relevant contracts, verify the candidate provider, and publish results against that provider’s exact version and branch.</li><li><strong>Before deployment:</strong> Check the candidate’s compatibility with the target environment.</li><li><strong>After deployment completes:</strong> Record which application version is now running there.</li></ol><p>A Git commit SHA works as the version when it uniquely identifies the tested artifact. If the same commit can produce meaningfully different artifacts, I use an identifier that distinguishes those builds.</p><p>Contract selection is where many setups become misleading. Checking only the newest consumer contract can miss an older client that still runs in production. Pact’s <a href="https://docs.pact.io/provider/recommended_configuration?utm_source=chatgpt.com">recommended provider configuration</a> includes the consumer’s main branch and, once deployments are tracked, deployedOrReleased versions. Matching feature branches can provide additional development feedback. <a href="https://docs.pact.io/provider/recommended_configuration?utm_source=chatgpt.com">Pact Docs</a></p><p>For the deployment gate, the <a href="https://docs.pact.io/pact_broker/can_i_deploy?utm_source=chatgpt.com">Pact Broker CLI</a> supports:</p><pre>pact-broker can-i-deploy \<br>  --pacticipant pricing-service \<br>  --version &quot;${APP_VERSION:?}&quot; \<br>  --to-environment production \<br>  --retry-while-unknown 12 \<br>  --retry-interval 10</pre><p>Here, CI supplies APP_VERSION from the tested artifact, and the Broker URL and credentials are already configured. The pipeline must stop if the command fails. Both consumers and providers need this gate. <a href="https://docs.pact.io/pact_broker/can_i_deploy?utm_source=chatgpt.com">docs.pact.io</a></p><p>The retry options provide bounded polling while verification results are missing. They do not turn a known incompatibility into success. I distinguish “verification is still running” from “verification failed” in pipeline output so engineers know whether to wait or investigate. <a href="https://docs.pact.io/pact_broker/client_cli/readme?utm_source=chatgpt.com">Pact Docs</a></p><p>After the rollout completes successfully, record it:</p><pre>pact-broker record-deployment \<br>  --pacticipant pricing-service \<br>  --version &quot;${APP_VERSION:?}&quot; \<br>  --environment production</pre><p>“Completes” matters. During a rolling deployment, requests may still reach old provider instances. Recording the new version too early can allow a consumer requiring new behavior to deploy while some instances cannot provide it.</p><p>Pact’s <a href="https://docs.pact.io/pact_broker/recording_deployments_and_releases?utm_source=chatgpt.com">deployment guidance</a> therefore places recording at the end, after the previous version is no longer running. Rollbacks also need updated deployment records. <a href="https://docs.pact.io/pact_broker/recording_deployments_and_releases?utm_source=chatgpt.com">Pact Docs</a></p><p>I treat that metadata as part of the deployment mechanism. Stale records make a carefully implemented compatibility check answer the wrong question.</p><h3>4. Let new requirements fail without freezing teams</h3><p>Now suppose checkout adds a contract requiring discountBreakdown, but pricing has not implemented it yet.</p><p>If publishing that contract immediately breaks every pricing build, checkout has acquired an accidental veto over unrelated provider releases. The provider may still satisfy every deployed consumer.</p><p>Pact’s <a href="https://docs.pact.io/pact_broker/advanced_topics/pending_pacts?utm_source=chatgpt.com">pending contracts</a> address this. In the regular provider verification workflow, a contract pending for that provider branch can fail verification without failing the overall verification task. The failed result still reaches the Broker, so the consumer requiring that behavior remains blocked from deployment.</p><p>Once the contract has been successfully verified on the provider branch, later failures of that accepted contract can fail the verification task. Branch metadata is essential to applying this behavior correctly. <a href="https://docs.pact.io/pact_broker/advanced_topics/pending_pacts?utm_source=chatgpt.com">Pact Docs</a></p><p>I enable pending support for the provider’s regular contract suite and keep deployment checks mandatory. That gives new requirements somewhere to exist before implementation without allowing consumers to ship unsupported assumptions.</p><p>For a response-field migration, I prefer an additive sequence: the provider introduces the new field while retaining the old one, consumers migrate, and the provider removes the old field after supported consumers no longer require it.</p><p>Contracts make that migration visible. Teams still need to agree on the meaning of the new field and the conditions for retiring the old one.</p><h3>5. Keep the guarantees narrow enough to trust</h3><p>There is a subtle gap worth testing deliberately: Pact generally permits additional fields in JSON responses. A minimal contract can therefore pass provider verification even if the real consumer’s deserializer rejects unknown fields. Its mock response never contained the new field that would trigger the failure.</p><p>That follows from Pact’s documented <a href="https://docs.pact.io/getting_started/matching?utm_source=chatgpt.com">response-matching behavior</a>. I add a consumer test with extra response fields or configure the decoder to tolerate them deliberately. <a href="https://docs.pact.io/getting_started/matching?utm_source=chatgpt.com">Pact Docs</a></p><p>I also keep pricing calculations, concurrent updates, retry behavior, and idempotency in tests designed for those properties. A contract can describe a conflict response without proving that two simultaneous requests produce the correct conflict.</p><p>A small deployed smoke test remains useful for routing, configuration, and credentials. Contract verification cannot demonstrate behavior in infrastructure it never exercised.</p><p>This workflow also has a cost. If two components always ship together, a local integration test may provide enough confidence with less machinery. For a public API with unidentified consumers, consumer-driven contracts cannot establish compatibility with every client. Pact’s own <a href="https://docs.pact.io/getting_started/what_is_pact_good_for?utm_source=chatgpt.com">suitability guidance</a> emphasizes identifiable, collaborating consumer and provider teams. <a href="https://docs.pact.io/getting_started/what_is_pact_good_for?utm_source=chatgpt.com">Pact Docs</a></p><p>I start with one integration where independent releases create recurring uncertainty. Success means a useful failure identifies the affected client, the violated expectation, and the candidate version before deployment.</p><p>Tomorrow, take one API call your checkout depends on, remove a required response field in a test branch, and make the resulting contract failure block that provider version from deployment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d16c27fb41ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST API Design Rules for Teams That Ship Fast]]></title>
            <link>https://medium.com/@teja230/rest-api-design-rules-for-teams-that-ship-fast-4c7e7726593e?source=rss-895cec4be077------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c7e7726593e</guid>
            <dc:creator><![CDATA[Raviteja Kapalavayi]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 14:31:02 GMT</pubDate>
            <atom:updated>2026-10-30T14:31:02.001Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Predictable errors, stable pagination, safe retries, and changes older clients can survive.</em></p><p>Imagine a checkout request that creates an order, commits the transaction, and loses its response on the way back. The customer retries. Your API creates another order because both requests were perfectly valid.</p><p>The endpoint passed its happy-path tests. The contract never explained what should happen when the caller cannot tell whether the operation succeeded.</p><p>My position is simple: teams that ship quickly should give individual services very little freedom over their public API conventions. Every custom error shape, pagination rule, or retry policy creates another decision for every consumer.</p><p>I want engineers spending that attention on pricing and fulfillment behavior. The surrounding contract should already be settled.</p><p>Here are the five rules I would establish for a hypothetical commerce API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFdygP63n-ZK0Ja2BCROkQ.png" /></figure><h3>1. Give errors a contract clients can act on</h3><p>An error response needs to support a decision: fix the request, refresh state, retry safely, or stop.</p><p>I use <a href="https://www.rfc-editor.org/rfc/rfc9457.html?utm_source=chatgpt.com">RFC 9457 Problem Details</a> as the response format, with application/problem+json. Its type identifies the problem; detail explains this occurrence. The specification explicitly discourages clients from parsing detail for structured information. <a href="https://www.rfc-editor.org/rfc/rfc9457.html?utm_source=chatgpt.com">rfc-editor.org</a></p><p>For a checkout request carrying an outdated cart version in its body, my contract returns HTTP 409 with a response like this:</p><pre>{<br>  &quot;type&quot;: &quot;https://api.example.com/problems/cart-version-conflict&quot;,<br>  &quot;title&quot;: &quot;Cart version conflict&quot;,<br>  &quot;status&quot;: 409,<br>  &quot;detail&quot;: &quot;Refresh the cart before submitting checkout again.&quot;,<br>  &quot;instance&quot;: &quot;urn:uuid:1d853ae2-8c95-40c1-a248-f95e0231d541&quot;,<br>  &quot;currentVersion&quot;: 13<br>}</pre><p>The client branches on the stable problem type. We can improve the explanation without breaking its control flow. The occurrence identifier lets support correlate the failure with internal logs without exposing stack traces.</p><p>I also document the distinction between malformed input, a business-state conflict, and an unexpected server failure. Returning 200 for all three makes HTTP-level monitoring less useful and pushes interpretation into every client.</p><p>In Spring, <a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-ann-rest-exceptions.html?utm_source=chatgpt.com">ProblemDetail and centralized exception handling</a> provide the building blocks. Authentication filters and gateways need compatible error handling too; controller advice alone cannot normalize failures produced outside MVC. <a href="https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-ann-rest-exceptions.html?utm_source=chatgpt.com">docs.spring.io</a></p><p>I avoid a universal retryable boolean. A temporary failure can still follow a committed write. Retry safety depends on the operation’s contract as well as the failure.</p><h3>2. Make pagination behavior explicit before data grows</h3><p>Suppose an order-history screen retrieves 50 records at a time, newest first. Between the first and second requests, a new order arrives. With offset pagination, the boundary shifts, and a record from the first page can appear again.</p><p>For frequently changing collections, I prefer keyset pagination with an immutable sort key and a unique tie-breaker. Ordering by createdAt alone leaves ties unresolved.</p><p>This illustrative PostgreSQL query fetches a subsequent page:</p><pre>SELECT id, created_at, status<br>FROM orders<br>WHERE tenant_id = :tenantId<br>  AND (created_at, id) &lt; (:createdAt, :id)<br>ORDER BY created_at DESC, id DESC<br>LIMIT :fetchLimit;</pre><p>Assume created_at and id are non-null and immutable, with an index on (tenant_id, created_at DESC, id DESC). The first-page query omits the cursor predicate. The tenant comes from authenticated context.</p><p>Fetch one extra row to detect another page, return the requested number, and build the next cursor from the last returned row. Document the default and maximum page sizes, plus an explicit end condition such as nextCursor: null.</p><p><a href="https://www.postgresql.org/docs/current/queries-limit.html?utm_source=chatgpt.com">PostgreSQL’s documentation</a> explains both the need for a unique ordering and why large offsets can be inefficient: skipped rows still require computation. <a href="https://www.postgresql.org/docs/current/queries-limit.html?utm_source=chatgpt.com">postgresql.org</a></p><p>Keep the cursor opaque and bind it to the tenant, filters, and sort order. Reject attempts to reuse it with incompatible query parameters. <a href="https://google.aip.dev/158?utm_source=chatgpt.com">Google’s pagination guidance</a> also makes an easily missed point: a page token must not confer authorization. Authorize every page independently. <a href="https://google.aip.dev/158?utm_source=chatgpt.com">google.aip.dev</a></p><p>There is another limit: keyset pagination does not create a snapshot. An order can change status between requests and enter or leave a filtered result. An exact export needs a snapshot-backed process or materialized results with defined consistency guarantees.</p><p>Offset pagination remains reasonable for small administrative datasets, especially when users need numbered pages and can tolerate movement. Choose the behavior the screen needs.</p><h3>3. Put idempotency inside the write boundary</h3><p>A header named Idempotency-Key does nothing until the server enforces a policy.</p><p>For order creation, I require the client to generate one key per intended operation and reuse it across retries. Generating a fresh key after every timeout defeats the mechanism.</p><p>My contract specifies four outcomes:</p><ul><li>The same key and equivalent request return the recorded completed outcome.</li><li>The same key with a different request returns a documented conflict.</li><li>Concurrent requests with the same key cannot both execute the mutation.</li><li>Key retention has a documented duration and behavior after expiration.</li></ul><p>Scope the key by authenticated tenant, caller, and operation. Store a fingerprint of the validated, canonical request, so JSON whitespace or field order does not create a false mismatch. Reauthorize access before replaying an outcome. Check for a recorded outcome before re-evaluating mutable business rules; a successful checkout may already have changed the cart.</p><p>For a write contained in PostgreSQL, I put the idempotency record, order, and replayable result in the same transaction. A <a href="https://www.postgresql.org/docs/current/index-unique-checks.html?utm_source=chatgpt.com">unique constraint arbitrates competing claims</a>. Only the request that acquires the claim executes the mutation; a competitor waits within a bounded budget or receives a documented in-progress response. <a href="https://www.postgresql.org/docs/current/index-unique-checks.html?utm_source=chatgpt.com">postgresql.org</a></p><p>This closes a dangerous gap in the common “write the order, then cache the response in Redis” approach. A crash between those steps leaves an order without a deduplication record. An expiring lock has a similar problem if execution outlives its lease.</p><p>External effects need their own recovery design. A local database transaction cannot atomically commit a payment provider’s action. I persist the intent to request payment and use the provider’s idempotency contract, with reconciliation for uncertain outcomes. When publishing events, a <a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html?utm_source=chatgpt.com">transactional outbox</a> preserves the intent to publish; consumers still need to handle duplicate delivery. <a href="https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html?utm_source=chatgpt.com">AWS Prescriptive Guidance</a></p><p>Response replay is also a policy choice. <a href="https://docs.stripe.com/api/idempotent_requests?utm_source=chatgpt.com">Stripe’s API v1 documentation</a> describes storing the initial status and body after execution begins, including 500 responses. Document which failures your API retains and how callers discover an unresolved operation’s outcome. <a href="https://docs.stripe.com/api/idempotent_requests?utm_source=chatgpt.com">docs.stripe.com</a></p><p>Finally, finite retention means finite protection. If an expired key can create another order, a permanent business constraint may also be necessary, such as one order per checkout session.</p><p><a href="https://www.rfc-editor.org/rfc/rfc9110.html#section-9.2.2">HTTP idempotency</a> concerns the intended effect of repeated requests; identical response bodies are not required. Make any stronger replay guarantee explicit. <a href="https://www.rfc-editor.org/rfc/rfc9110.html?utm_source=chatgpt.com">rfc-editor.org</a></p><h3>4. Review compatibility through an older client’s eyes</h3><p>“We only added a field” is an incomplete compatibility argument.</p><p>Suppose an order response adds the status ON_HOLD. A Java client with a closed enum may fail during deserialization, before its business logic can apply any fallback.</p><p><a href="https://google.aip.dev/180?utm_source=chatgpt.com">Google’s compatibility guidance</a> calls out response enum additions as a risk. If values can expand, document that expectation and test unknown-value handling in supported clients. For an order workflow, an unknown status should lead to a conservative display or review path; it should never accidentally authorize fulfillment. <a href="https://google.aip.dev/180?utm_source=chatgpt.com">google.aip.dev</a></p><p>Optional request fields can also change behavior. Imagine adding includeCancelled, defaulting to false, to an endpoint that previously returned canceled orders. An unchanged request now receives different results.</p><p>Adding pagination later creates the same trap. An older client that previously received every order may silently process only the first page. The JSON still parses. The reconciliation job is still wrong. <a href="https://google.aip.dev/158?utm_source=chatgpt.com">google.aip.dev</a></p><p>I review three things together: the schema, the behavior of existing requests, and the behavior of supported client implementations. Schema-diff checks catch removed fields and type changes. Consumer tests catch assumptions about defaults, enum handling, ordering, and error behavior.</p><p>For a field migration, add the replacement, preserve the existing field’s meaning, migrate consumers, and measure remaining usage before removal. If the behavior genuinely cannot coexist, introduce an explicit version boundary with a migration window.</p><p>A version number alone does not tell you whether an old mobile app still depends on the previous contract.</p><h3>5. Standardize names and their meaning</h3><p>I choose plural resource paths, one JSON naming convention, and explicit units. For this API, that means /orders, createdAt, and a money representation containing amountMinor and currency.</p><p>In an illustrative USD amount, 1299 minor units means $12.99. A field named amount leaves too much room for a client to interpret that number differently. The currency contract must define the applicable minor unit.</p><p>Consistency also requires domain vocabulary. A promotion rule, a coupon code, and an applied discount are different concepts. Giving all three the same name creates confusion even when every field uses perfect camelCase.</p><p>I keep paths independent of database structure. A public resource should survive a table split or a service migration. When a workflow deserves a resource, such as a cancellation request with its own status, model that lifecycle explicitly.</p><p>Then I put the conventions in the starter template: the shared error format, pagination response, cursor handling, and contract checks. Keep shared libraries focused on protocol behavior so services can evolve their domain models independently.</p><p>There are reasonable exceptions. A prototype with one caller deployed alongside it can use a lighter compatibility policy. An integration with an established external API may need its conventions at that boundary. Neither case justifies surprising consumers that deploy independently.</p><p>The most valuable enforcement is a test of the failure the contract promises to handle.</p><p>Tomorrow, add one contract test that drops an order-creation response after commit, retries with the same key, and proves the caller receives the original order without creating another.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c7e7726593e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL in Microservices: Where It Shines and Hurts]]></title>
            <link>https://medium.com/@teja230/graphql-in-microservices-where-it-shines-and-hurts-cd820530ceab?source=rss-895cec4be077------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd820530ceab</guid>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Raviteja Kapalavayi]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 14:31:02 GMT</pubDate>
            <atom:updated>2026-10-28T14:31:02.204Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why I start with a BFF, and what federation demands from batching, caching, authorization, and schema ownership.</em></p><p>Imagine a cart screen that replaces several frontend requests with one GraphQL operation. Behind that endpoint, 20 cart lines still trigger 41 service calls. The browser sees a cleaner API; the backend sees a small networking festival.</p><p>I like GraphQL when different clients need different combinations of the same business capabilities. A mobile cart can request a compact summary while a desktop checkout requests delivery estimates and promotion details, without requiring a new endpoint for every variation.</p><p>But my default for a microservice architecture is a product-focused GraphQL backend for frontend, or BFF. Federation earns its place when independent teams need to share ownership of a graph. The number of services is a poor reason to adopt it.</p><p>The difficult part is making one schema behave predictably across several owners, latency budgets, and definitions of “this user can see this value.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FGnXPuO5aat0VF5hNqbHJA.png" /></figure><h3>Make federation earn its organizational cost</h3><p>For a hypothetical commerce application, I would start with a checkout BFF that composes cart, catalog, pricing, and delivery APIs. The checkout team owns the client contract and its performance. Domain services retain their business rules and can expose REST or RPC internally.</p><p>That arrangement gives one team room to evolve the checkout experience. It also creates a bottleneck if every domain team must wait for that team to expose new capabilities.</p><p>Federation becomes attractive when several teams repeatedly contribute reusable capabilities to multiple experiences. Catalog can evolve product information, pricing can evolve quotes, and delivery can evolve promises through separately managed subgraphs. The <a href="https://graphql.org/learn/federation/?utm_source=chatgpt.com">GraphQL federation guide</a> describes this organizational fit and the infrastructure needed to support it. <a href="https://graphql.org/learn/federation/?utm_source=chatgpt.com">GraphQL</a></p><p>BFFs and federation can coexist. A BFF defines an experience boundary; federation distributes schema implementation. A mobile BFF might consume a federated graph, provided that extra layer has a concrete purpose.</p><p>Neither approach settles semantic ownership automatically. Does Product.price mean the list price, a customer-specific offer, or the amount after a cart-wide promotion? Those are different contracts. I prefer a contextual price quote over a deceptively universal product field.</p><p>There is a useful detail here: <a href="https://www.apollographql.com/docs/graphos/schema-design/federated-schemas/entities/enforce-ownership?utm_source=chatgpt.com">Apollo Federation 2 does not inherently designate one subgraph as the owner of an entire entity</a>. Multiple subgraphs can contribute fields. Organizational accountability still needs an explicit decision. <a href="https://www.apollographql.com/docs/graphos/schema-design/federated-schemas/entities/enforce-ownership?utm_source=chatgpt.com">Apollo GraphQL Docs</a></p><p>For each published field, I want a team responsible for its meaning, access policy, latency, and deprecation. A successful schema composition cannot assign the on-call rotation.</p><h3>Batch the work behind the schema</h3><p>Return to the hypothetical 20-line cart. Assume distinct products, one cart request, one catalog lookup per line, and one price lookup per line. That is 1 + 20 + 20 = 41 downstream requests.</p><p>With genuine bulk catalog and pricing APIs, the same operation could use three requests: one cart fetch and two batch fetches. That calculation assumes the entire cart fits within both batch limits and no additional dependencies are needed. It is an illustrative call count, not a latency benchmark.</p><p>Federation does not guarantee that result. A router can send several entity references in one subgraph request while the receiving service performs one database lookup per entity. <a href="https://www.apollographql.com/docs/graphos/schema-design/guides/handling-n-plus-one?utm_source=chatgpt.com">Apollo’s N+1 guidance</a> covers this gap between router batching and data-source batching. <a href="https://www.apollographql.com/docs/graphos/schema-design/guides/handling-n-plus-one?utm_source=chatgpt.com">Apollo GraphQL Docs</a></p><p>In Spring GraphQL, <a href="https://docs.spring.io/spring-graphql/reference/controllers.html#controllers.batch-mapping">@BatchMapping</a> provides a concise implementation for straightforward associations. This partial controller method maps cart lines to products: <a href="https://docs.spring.io/spring-graphql/reference/controllers.html?utm_source=chatgpt.com">docs.spring.io</a></p><pre>@BatchMapping(typeName = &quot;CartLine&quot;, field = &quot;product&quot;)<br>public Map&lt;CartLine, Product&gt; products(<br>        List&lt;CartLine&gt; lines,<br>        @ContextValue(&quot;viewer&quot;) Viewer viewer) {<br>    var ids = lines.stream()<br>            .map(CartLine::productId)<br>            .distinct()<br>            .toList();<br>    var products = catalog.findVisibleByIds(viewer, ids);<br>    var result = new HashMap&lt;CartLine, Product&gt;();<br>    for (var line : lines) {<br>        result.put(line, products.get(line.productId()));<br>    }<br>    return result;<br>}</pre><p>The domain types and injected catalog adapter are omitted. Assume immutable CartLine records, a nullable product field, and trusted viewer context established during authentication. The adapter performs a bulk read, authorizes each requested product, and omits unavailable products from its returned map. This synchronous example adds no retries or cross-service transaction.</p><p>The important work is inside findVisibleByIds. A loop containing 20 HTTP calls remains 20 HTTP calls, regardless of the annotation above it.</p><p>Batching also cannot remove a real dependency. In an illustrative plan, a 15 ms cart fetch followed by independent 25 ms catalog and 40 ms pricing fetches takes approximately 15 + max(25, 40) = 55 ms, excluding overhead. If pricing first needs catalog output, the path becomes 15 + 25 + 40 = 80 ms.</p><p><a href="https://www.apollographql.com/docs/graphos/schema-design/federated-schemas/reference/query-plans?utm_source=chatgpt.com">Apollo query plans expose parallel and sequential fetches</a>. I review those plans alongside database and outbound HTTP spans. Counting client requests alone misses most of the work. <a href="https://www.apollographql.com/docs/graphos/schema-design/federated-schemas/reference/query-plans?utm_source=chatgpt.com">Apollo GraphQL Docs</a></p><h3>Cache according to who can see the answer</h3><p>“Add Redis” is an incomplete caching strategy for a graph that mixes public product names with personalized prices.</p><p>I separate request memoization, shared domain caching, and whole-response caching because they have different correctness rules.</p><p>A request-scoped DataLoader avoids fetching the same key repeatedly during an operation. Its cache is deliberately short-lived. The <a href="https://github.com/graphql/dataloader#caching-per-request">DataLoader documentation</a> warns against sharing loader instances across requests with different users. A singleton loader can turn a performance optimization into a data leak. <a href="https://github.com/graphql/dataloader?utm_source=chatgpt.com">GitHub</a></p><p>Even within one request, keys must distinguish different results. If an operation requests prices in two currencies, a price loader keyed only by product ID is insufficient.</p><p>Shared domain caches need keys derived from the inputs that affect the result. Product content might vary by tenant and locale. A quote might depend on quantity, currency, customer eligibility, coupons, and the rest of the cart. I avoid caching quotes across requests until those dependencies and their invalidation rules are explicit.</p><p>Whole-response caching adds another constraint: the response combines the policies of its fields. For example, <a href="https://www.apollographql.com/docs/apollo-server/performance/caching?utm_source=chatgpt.com">Apollo Server’s cache-control behavior</a> uses the lowest field lifetime and makes the response private if any included field is private. These are implementation rules to configure and verify, not universal GraphQL guarantees. <a href="https://www.apollographql.com/docs/apollo-server/performance/caching/?utm_source=chatgpt.com">Apollo GraphQL Docs</a></p><p>Consider public catalog content that can tolerate five minutes of staleness combined with a customer-specific offer that must not be cached. Under those rules, the combined response loses whole-response caching.</p><p>My recommendation is to consider separate operations for stable public content and volatile personalized data, or cache the domain reads beneath the graph. An extra client request can be a reasonable price for substantially more reusable cached data. One request should be a convenience, never the performance target by itself.</p><h3>Authorize every route to the same object</h3><p>Authenticating at the gateway answers who sent the request. It does not establish that the caller may read every object reachable through the graph.</p><p>Suppose a cart is accessible through cart(id), an account’s cart collection, and a federated entity lookup. Checking ownership only in the first resolver leaves other paths dependent on accidental protections.</p><p>I put the authoritative access policy in the business layer that owns the data, consistent with the <a href="https://graphql.org/learn/authorization/?utm_source=chatgpt.com">GraphQL authorization guidance</a>. Every resolver and batch adapter must use that policy. Tenant filtering belongs in the actual data access path, not just the initial root resolver. <a href="https://graphql.org/learn/authorization/?utm_source=chatgpt.com">GraphQL</a></p><p>The gateway should propagate trusted identity and tenant context over an authenticated internal connection. A tenant header supplied by the client needs verification before it becomes authority. Entity identifiers locate data; they do not grant permission to read it.</p><p>Caching must preserve the same boundary. Authenticating before a shared cache lookup is insufficient if the key lets two callers with different permissions receive the same private result. Sensitive cache hits need an appropriate authorization check and permission-change invalidation strategy, or the response should remain uncached.</p><p>I also budget the work an authorized caller can request. A shallow query for 100 orders with 100 lines each can still reach 10,000 line objects. Depth limits alone do not describe that cost.</p><p>For first-party clients, I favor reviewed operation allowlists alongside bounded pagination, cost limits, and deadlines. These controls complement object authorization; the <a href="https://graphql.org/learn/security/?utm_source=chatgpt.com">GraphQL security guide</a> treats demand control as a separate concern. A legitimate user can still accidentally submit an expensive operation. <a href="https://graphql.org/learn/security/?utm_source=chatgpt.com">GraphQL</a></p><h3>Make failure behavior part of schema ownership</h3><p>Nullability deserves the same attention as a timeout configuration.</p><p>Consider this illustrative schema excerpt, with the referenced types defined elsewhere:</p><pre>type Query {<br>  cart(id: ID!): Cart<br>}</pre><pre>type Cart {<br>  id: ID!<br>  lines: [CartLine!]!<br>  deliveryEstimate: DeliveryEstimate!<br>}</pre><p>If the selected deliveryEstimate field raises an execution error, its non-null contract propagates that failure to cart. Because cart is nullable, the client receives cart: null, even if the lines loaded successfully. That follows the <a href="https://spec.graphql.org/September2025/#sec-Handling-Execution-Errors">GraphQL specification’s error-propagation rules</a>. <a href="https://spec.graphql.org/September2025/?utm_source=chatgpt.com">spec.graphql.org</a></p><p>Making deliveryEstimate nullable permits the cart to survive that failure. The trade-off is an explicit client obligation to handle unavailable delivery information. I choose that contract when the screen can remain useful without the estimate; I keep stricter guarantees when the operation would otherwise present misleading information.</p><p>I also measure partial GraphQL errors and required-field availability, alongside latency and transport failures. Operation identifiers, subgraph timings, and downstream call counts make incidents diagnosable. A successful HTTP response alone does not tell me whether checkout rendered usable data.</p><p>Before a field change ships, I want composition checks, compatibility checks against supported client operations, and an owner reviewing changes to meaning and execution cost. Adding a field can preserve schema compatibility while making a frequently used operation much more expensive once clients select it. Deprecation needs usage evidence over the supported client lifecycle, including older mobile versions.</p><p>My BFF preference stops being useful when one team becomes a permanent queue for independent domain teams. That is a strong reason to federate. Conversely, a fixed bulk export or a simple internal command may be better served by a job API or ordinary RPC.</p><p>For checkout writes, GraphQL can expose placeOrder, but the owning service must handle idempotency, current price validation, and recovery from partial failures. <a href="https://www.apollographql.com/docs/graphos/schema-design/guides/distributed-orchestration?utm_source=chatgpt.com">Federation does not supply distributed transaction semantics</a>. I keep those guarantees explicit in the command implementation. <a href="https://www.apollographql.com/docs/graphos/schema-design/guides/distributed-orchestration?utm_source=chatgpt.com">Apollo GraphQL Docs</a></p><p>Tomorrow, trace your busiest GraphQL operation with its owning team and record its downstream call count, authorization boundary, cache scope, and expected response when its slowest dependency fails.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd820530ceab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feature Flags Done Right: How to Avoid “Flag Debt”]]></title>
            <link>https://medium.com/@teja230/feature-flags-done-right-how-to-avoid-flag-debt-a8f57b86f0a1?source=rss-895cec4be077------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8f57b86f0a1</guid>
            <dc:creator><![CDATA[Raviteja Kapalavayi]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 14:31:01 GMT</pubDate>
            <atom:updated>2026-10-26T14:31:01.654Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Ship gradually, assign ownership, and make cleanup part of delivery.</em></p><p>A feature ships behind a flag.</p><p>The rollout reaches 100%. The dashboard looks healthy. The team moves to the next priority.</p><p>Six months later, someone asks:</p><p>“Can we delete this flag?”</p><p>Nobody knows.</p><p>The original author has changed teams. The old implementation still compiles. A background job might depend on it. Someone remembers an incident where turning it off helped — but cannot remember whether that still works.</p><p>The flag took minutes to add. Removing it now requires an investigation.</p><p>That is flag debt: the accumulated cost of keeping conditional behavior after its purpose becomes unclear.</p><p>Feature flags are valuable because they separate deployment from release. But every flag introduces another decision the system — and its maintainers — must understand.</p><p>The way to control that complexity starts before the first flag check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLIk6SLMcmhNZ__IC5ESig.png" /></figure><p><strong>Start by deciding whether the flag is temporary.</strong></p><p>A release flag and an emergency kill switch have different jobs. Giving them the same expiration policy creates unnecessary work or leaves temporary branches alive indefinitely.</p><p>Pete Hodgson’s feature-toggle taxonomy distinguishes release, experiment, operational, and permissioning toggles, with longevity and decision dynamism helping determine how to manage them.</p><p>Here is the practical policy I would build around that distinction:</p><p>PurposeExpected lifetimeCompletion conditionRelease rolloutTemporaryIntended behavior is stable across the target populationExperimentTemporaryAnalysis is complete and a decision is recordedMigrationTemporary, with explicit phasesConsumers have migrated and compatibility requirements are satisfiedOperational kill switchPotentially permanentPeriodically reviewed and exercisedProduct entitlementLong-lived policyProduct access rules change or the capability retires</p><p>A permanent control is not automatically debt. An unexplained control with no owner is.</p><p>Also, a flag that hides a paid feature is not sufficient authorization. The backend must still enforce access.</p><p><strong>Give every flag an owner and an exit condition.</strong></p><p>A useful flag record should answer:</p><ul><li>Why does this exist?</li><li>Which team owns its behavior and removal?</li><li>What is the impact of a bad change?</li><li>What happens when evaluation cannot return a usable value?</li><li>When must the team review it?</li><li>What evidence makes removal safe?</li></ul><p>For a hypothetical fulfillment service, the record could look like this:</p><p>FieldExampleKeyfulfillment.network-routing-v2TypeTemporary release flagOwnerFulfillment PlatformRiskHigh: affects order allocationInitial fallbackLegacy routing, while compatibility holdsReview dateNovember 15Exit conditionFull rollout, agreed stability window, compatibility checks completeCleanup ticketLinked before rollout begins</p><p>Assign ownership to a durable team. An individual can drive the rollout, but ownership should survive a transfer or vacation.</p><p>Treat the review date as a prompt for a decision. Automatically switching off an expired production flag could cause the very incident the flag was created to prevent.</p><p>The valid outcomes are straightforward: remove it, extend it with a reason, or explicitly classify it as a maintained control.</p><p><strong>Define “done” beyond 100% rollout.</strong></p><p>I would use six lifecycle states:</p><ol><li><strong>Defined:</strong> Purpose, owner, risk, and exit condition exist.</li><li><strong>Implemented:</strong> Both paths and failure behavior are tested.</li><li><strong>Rolling out:</strong> Exposure increases with observable guardrails.</li><li><strong>Stable:</strong> The intended population receives the selected behavior.</li><li><strong>Removing:</strong> Obsolete code, tests, and configuration are being removed.</li><li><strong>Archived:</strong> Supported running versions no longer need the flag.</li></ol><p>A canceled rollout also needs cleanup: retain the old behavior and remove the abandoned implementation.</p><p>Unleash provides lifecycle stages and stale-flag signals that can support this process. Its stale-state events can also trigger downstream automation.</p><p>The critical distinction is between <em>stable</em> and <em>finished</em>.</p><p>At 100%, the release may be complete. The engineering work still includes removing the temporary decision.</p><p><strong>Match the controls to the consequences.</strong></p><p>A copy experiment and a payment-routing change should not require identical release processes.</p><p>This is a proposed starting policy, not an industry standard:</p><p>Risk tierExampleSuggested controlsLowCosmetic presentationOwner, basic verification, simple rollbackMediumSearch ranking or recommendationsStable cohorts, staged exposure, outcome monitoringHighCheckout, inventory, fulfillment routingPeer review, compatibility checks, explicit stop conditions, tested recoveryCriticalAuthorization or irreversible writesSpecialist review, strict change access, audit trail, recovery beyond toggling</p><p>Risk depends on reversibility and downstream effects as much as traffic percentage.</p><p>One percent of requests can still corrupt important data.</p><p>For a high-risk rollout, define what would make you stop before you start. Depending on the feature, that might include duplicate allocations, increased errors, latency regression, or divergence between expected and actual business results.</p><p>A flag can stop future execution of a path. It cannot automatically undo a charge, recall an event, or repair a database write.</p><p><strong>Keep the decision in one place.</strong></p><p>In a Java service, scattered flag checks make cleanup harder because each caller can develop slightly different assumptions.</p><p>A better approach is to evaluate at a clear boundary and choose an implementation:</p><pre>public ShippingQuote quote(Order order) {<br>    RoutingContext context =<br>        RoutingContext.fromTrustedOrder(order);</pre><pre>    boolean useNetworkRouting =<br>        routingFlags.useNetworkRouting(context);</pre><pre>    ShippingRouter router = useNetworkRouting<br>        ? networkRouter<br>        : legacyRouter;</pre><pre>    return router.quote(order);<br>}</pre><p>Here, routingFlags is an application-owned abstraction. It centralizes the flag key, evaluation context, and documented fallback behavior.</p><p>Once the rollout is complete, cleanup becomes:</p><pre>public ShippingQuote quote(Order order) {<br>    return networkRouter.quote(order);<br>}</pre><p>The old router can then be removed if no other callers need it.</p><p>For workflows spanning multiple services, decide whether the choice must remain stable throughout the operation. An order should not switch routing strategies halfway through processing because configuration changed.</p><p>When consistency is required, persist an explicit workflow version or decision with the order and validate it downstream.</p><p><strong>Test the configurations that matter.</strong></p><p>With ten independent Boolean flags, there are 1,024 theoretical combinations. Exhaustively testing every combination quickly becomes impractical.</p><p>Focus on:</p><ul><li>The current production configuration.</li><li>The next intended rollout configuration.</li><li>The supported rollback configuration.</li><li>Evaluation failures and fallback behavior.</li><li>Known interactions between flags.</li></ul><p>Test both branches while both remain supported. After cleanup, retain tests for the chosen behavior and remove tests that exist only for obsolete branching.</p><p>For migrations, verify that the rollback path can still read data written by the new path. A passing unit test for “flag off” does not prove that production rollback remains safe.</p><p><strong>Automate discovery and cleanup proposals.</strong></p><p>A useful cleanup job combines several signals:</p><ul><li>Flag metadata and review dates.</li><li>Targeting state across relevant environments.</li><li>Evaluation telemetry.</li><li>References in repositories.</li><li>Dependencies between flags.</li><li>Versions still deployed or supported.</li></ul><p>No single signal proves a flag is safe to remove.</p><p>No recent evaluations might mean dead code. It might also mean a monthly job has not run, telemetry is incomplete, or older clients are temporarily offline.</p><p>Likewise, no references on the main branch says little about an older release still running.</p><p>Automation should turn these signals into reviewable work:</p><ol><li>Identify candidates and explain why they were selected.</li><li>Notify the owning team through the normal work queue.</li><li>Open a cleanup PR where transformation is reliable.</li><li>Run relevant tests and compatibility checks.</li><li>Route the PR for review based on risk.</li><li>Verify deployment before proposing archival.</li></ol><p>Where available, use syntax-aware transformations instead of broad text replacement.</p><p>CI can require metadata for new flags and prevent new references to retired ones. For existing overdue flags, begin with warnings and assigned cleanup work; blocking every unrelated build often makes the policy harder to sustain.</p><p><strong>Remove code before archiving configuration.</strong></p><p>The safe sequence usually looks like this:</p><ol><li>Confirm the final behavior, including remaining targeting exceptions.</li><li>Remove obsolete branches and flag evaluations.</li><li>Deploy the cleanup to relevant services and workers.</li><li>Check supported older versions and the rollback window.</li><li>Resolve dependent flags.</li><li>Archive the flag and retain its audit history.</li></ol><p>LaunchDarkly explicitly warns that evaluating an archived flag returns the fallback value, making code cleanup before archival important.</p><p>This can produce a surprising failure: production uses the new path, but archiving the flag makes an old instance fall back to the legacy path.</p><p>Cleanup is a production change. Give it the same attention to deployment order that you give the rollout.</p><p><strong>Measure unfinished work, not just the number of flags.</strong></p><p>A useful dashboard would track:</p><ul><li>Temporary flags past their review date.</li><li>Flags without an owning team.</li><li>Time from stable rollout to deployed code removal.</li><li>Cleanup candidates waiting for review.</li><li>High-risk flags without a verified recovery procedure.</li><li>Permanent controls overdue for an exercise or review.</li></ul><p>Separate temporary flags from intentionally maintained controls. Otherwise, teams can improve the count while making operations less safe.</p><p>For temporary flags, the most revealing question is simple:</p><p><strong>How long after the rollout finishes does the unnecessary branch remain in production?</strong></p><p>That is where release work quietly becomes maintenance work.</p><p>Feature flags make it easier to introduce change gradually. Their lifecycle should make it equally clear how to finish.</p><p>Before adding the next flag, write down its owner, its failure behavior, and the evidence required to remove it.</p><p>The best time to plan that deletion is while everyone still remembers why the flag exists.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8f57b86f0a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>