<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Anass Ez-zouaine | Backend, AI &amp; Shopify Engineer | Architecture</title><description>Architecture posts from Anass Ez-zouaine | Backend, AI &amp; Shopify Engineer.</description><link>https://ansezz.com/</link><item><title>HITL gates for agent mutations</title><link>https://ansezz.com/blog/hitl-gates-for-agent-mutations/</link><guid isPermaLink="true">https://ansezz.com/blog/hitl-gates-for-agent-mutations/</guid><description>Human-in-the-loop risk gates for refunds, inventory, and spend. Verify mutations after tool calls so agents cannot declare early victory.</description><pubDate>Fri, 02 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Agents are optimistic. They call a tool, see a JSON blob that looks success-shaped, and tell the user &quot;refund sent.&quot;&lt;/p&gt;

- Refunds, inventory writes, spend and credential changes need a human or a policy gate.
- Approval ids come from your system, bound to actor, tenant, action and expiry. Never from the model.
- After every mutation, a second read proves the world moved before anyone says &quot;done.&quot;

&lt;p&gt;Sometimes the refund is pending. Sometimes the tool returned a structured error the model ignored. Sometimes the write never happened.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Human-in-the-loop (HITL) gates&lt;/strong&gt; and &lt;strong&gt;post-mutation verification&lt;/strong&gt; are how you stop early victory. The model can propose. Policy decides. The system checks reality before anyone celebrates.&lt;/p&gt;
&lt;p&gt;This is the mutation half of &lt;a href=&quot;https://ansezz.com/blog/mcp-first-is-the-new-mobile-first/&quot;&gt;MCP first&lt;/a&gt;: tools without judgment burn money.&lt;/p&gt;
&lt;p&gt;Pair with &lt;a href=&quot;https://ansezz.com/blog/mcp-idempotency-laravel-mutations/&quot;&gt;idempotency&lt;/a&gt;, &lt;a href=&quot;https://ansezz.com/blog/mcp-structured-tool-errors-laravel/&quot;&gt;structured tool errors&lt;/a&gt;, &lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;auth and audit&lt;/a&gt;, and commerce paths in &lt;a href=&quot;https://ansezz.com/blog/secure-agentic-commerce-shopify/&quot;&gt;secure agentic commerce&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Which mutations need a gate&lt;/h2&gt;
&lt;p&gt;Not every tool needs a human. Read-only lookups should be fast. Mutations that move money, stock, or trust should slow down.&lt;/p&gt;
&lt;figure&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Risk class&lt;/th&gt;
&lt;th&gt;Examples&lt;/th&gt;
&lt;th&gt;Default gate&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Money out&lt;/td&gt;
&lt;td&gt;Refunds, payouts, store credit&lt;/td&gt;
&lt;td&gt;Approve above threshold; auto only inside policy&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Inventory&lt;/td&gt;
&lt;td&gt;Force adjust, unpublish, bulk price&lt;/td&gt;
&lt;td&gt;Approve or dual-control for large deltas&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Spend / buy&lt;/td&gt;
&lt;td&gt;Agent checkout complete, ad spend&lt;/td&gt;
&lt;td&gt;Buyer confirm or spend ceiling&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Credentials&lt;/td&gt;
&lt;td&gt;Rotate keys, invite admins&lt;/td&gt;
&lt;td&gt;Always human for production&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Irreversible comms&lt;/td&gt;
&lt;td&gt;Mass email, legal notices&lt;/td&gt;
&lt;td&gt;Approve + preview&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Thresholds are product decisions. A small shipping adjustment is not the same as a large refund. Encode ceilings in policy config, not prompt text.&lt;/p&gt;
&lt;p&gt;For Shopify-style claims and refunds, the same idea shows up as queue triage with human resolution (&lt;a href=&quot;https://ansezz.com/blog/shopify-claims-pipeline-claimify/&quot;&gt;claims pipeline&lt;/a&gt;). Auto-clear the easy half; keep edge cases for people.&lt;/p&gt;

List every mutation tool you expose and tag each one with a risk class from the table above.

&lt;h2&gt;Gate shapes that work&lt;/h2&gt;
&lt;p&gt;There are four shapes that hold up in production:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Pre-tool approval:&lt;/strong&gt; agent prepares a &lt;code&gt;proposed_action&lt;/code&gt; payload; UI or Slack asks a human to approve; only then does &lt;code&gt;execute_refund&lt;/code&gt; run with the approval id.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Two-step tools:&lt;/strong&gt; &lt;code&gt;draft_refund&lt;/code&gt; (safe) then &lt;code&gt;commit_refund&lt;/code&gt; (requires &lt;code&gt;approval_token&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Async review queue:&lt;/strong&gt; mutation creates a &lt;code&gt;pending&lt;/code&gt; record; worker waits for approve/deny; agent polls status.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Policy auto-approve:&lt;/strong&gt; small, low-risk, fully validated cases skip the human but still write audit + verification.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Bind every approval&lt;/h3&gt;
&lt;p&gt;Always bind approvals to:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Actor (who asked)&lt;/li&gt;
&lt;li&gt;Tenant&lt;/li&gt;
&lt;li&gt;Exact action hash / idempotency key&lt;/li&gt;
&lt;li&gt;Expiry (stale approvals must not run tomorrow)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Do not let the model invent an &lt;code&gt;approval_id&lt;/code&gt;. Issue it from your system after a real human (or policy engine) decision.&lt;/p&gt;
&lt;h2&gt;Anti early-victory: verify after tools&lt;/h2&gt;
&lt;p&gt;The failure mode is consistent across stacks:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Tool returns something the model interprets as success.&lt;/li&gt;
&lt;li&gt;Model narrates completion to the user.&lt;/li&gt;
&lt;li&gt;Downstream system never applied the change (validation, partial write, wrong environment).&lt;/li&gt;
&lt;/ol&gt;

  &lt;div&gt;The tool returns something success-shaped and the agent tells the user &quot;refund sent.&quot;&lt;/div&gt;
  &lt;div&gt;The system reads the refund back, confirms amount and status, then the agent says &quot;done.&quot;&lt;/div&gt;

&lt;figure&gt;
&lt;h3&gt;What a second read looks like&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Verification&lt;/strong&gt; is a second read (or event) that proves the world moved:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;After refund: fetch order transactions / refund set; confirm amount and status.&lt;/li&gt;
&lt;li&gt;After inventory adjust: read InventoryLevel (or your source of truth); confirm quantity.&lt;/li&gt;
&lt;li&gt;After spend: read ledger entry or checkout status; confirm &lt;code&gt;completed&lt;/code&gt; not &lt;code&gt;open&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;After key rotate: confirm old key rejected and new key works in a dry probe.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Put verification in &lt;strong&gt;code&lt;/strong&gt; the agent must call (or that your tool runner calls automatically), not only in a skill paragraph.&lt;/p&gt;
&lt;p&gt;Skills help sequencing; code enforces it.&lt;/p&gt;
&lt;p&gt;Pattern for a tool runner:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;authorize -&amp;gt; idempotency begin -&amp;gt; mutate -&amp;gt; verify -&amp;gt; audit -&amp;gt; respond
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If verify fails, return a recoverable structured error (&lt;code&gt;verification_failed&lt;/code&gt;) with what was expected vs observed. Do not return a soft &quot;ok&quot; with a warning buried in prose.&lt;/p&gt;
&lt;h2&gt;Where HITL sits in MCP / UCP&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Your SaaS MCP:&lt;/strong&gt; gate inside the tool or a preceding approval tool; never expose bare Admin credentials to the model (&lt;a href=&quot;https://ansezz.com/blog/secure-agentic-commerce-shopify/&quot;&gt;secure agentic commerce&lt;/a&gt; for the commerce variant).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Shopify UCP checkout:&lt;/strong&gt; &lt;code&gt;complete_checkout&lt;/code&gt; already sits behind trust tiers and permissions (&lt;a href=&quot;https://ansezz.com/blog/ucp-agent-profiles-are-the-new-oauth-app/&quot;&gt;agent profiles&lt;/a&gt;, &lt;a href=&quot;https://ansezz.com/blog/buyer-linked-tokens-agent-checkout/&quot;&gt;buyer-linked tokens&lt;/a&gt;). Still verify order state before telling the buyer &quot;paid.&quot;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Laravel MCP:&lt;/strong&gt; combine gates with &lt;a href=&quot;https://ansezz.com/blog/mcp-idempotency-laravel-mutations/&quot;&gt;idempotency&lt;/a&gt; so a double-approved click cannot double-refund.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Stateless servers (&lt;a href=&quot;https://ansezz.com/blog/stateless-mcp-servers-laravel/&quot;&gt;stateless MCP&lt;/a&gt;) make this cleaner: approval records live in your DB, not in a vanished MCP session.&lt;/p&gt;
&lt;h2&gt;Implementation checklist&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;Classify tools: read / low-risk mutate / high-risk mutate.&lt;/li&gt;
&lt;li&gt;Define numeric ceilings per tenant for auto-approve.&lt;/li&gt;
&lt;li&gt;Require &lt;code&gt;approval_id&lt;/code&gt; (system-issued) on high-risk commits.&lt;/li&gt;
&lt;li&gt;Expire approvals; bind them to idempotency keys.&lt;/li&gt;
&lt;li&gt;Auto-verify after mutate; fail closed on mismatch.&lt;/li&gt;
&lt;li&gt;Audit propose, approve, execute, verify as separate events.&lt;/li&gt;
&lt;li&gt;Teach skills: &quot;never claim success without verify tool result.&quot;&lt;/li&gt;
&lt;li&gt;UX: show the human the exact payload (amount, SKU, customer) before approve.&lt;/li&gt;
&lt;/ol&gt;

Add an automatic verify step to your refund tool runner and make it fail closed on a mismatch.


- HITL gates belong on refunds, inventory writes, spend, and credential changes.
- Issue approval ids from your system; never trust model-invented tokens.
- Verify mutations with a second read before user-facing success copy.
- Encode ceilings and dual-control in policy config, not only prompts.
- Audit propose, approve, execute and verify as distinct events.
- Early victory is a product bug, not a charming agent quirk.

&lt;p&gt;When your agent last said &quot;all done,&quot; did the ledger agree within a second, or did a human discover the gap in a support ticket two days later?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>mcp</category><category>agentic-ai</category><category>security</category><category>architecture</category><category>ai</category><category>laravel</category></item><item><title>MCP first is the new mobile first</title><link>https://ansezz.com/blog/mcp-first-is-the-new-mobile-first/</link><guid isPermaLink="true">https://ansezz.com/blog/mcp-first-is-the-new-mobile-first/</guid><description>Mobile first made every screen work on a phone. MCP first makes every product capability work for an AI agent: tools, skills, and permissions before the human UI.</description><pubDate>Sun, 20 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Mobile first made products work on a phone. MCP first makes them work for an AI agent.&lt;/p&gt;

- The hard constraint used to be a small screen. Now it is whether an authorized agent can finish the job.
- Ship tools, permissions and skills first. The human UI becomes one client of the same capabilities.
- Start small: one sprint and three outcomes your users already ask for.

&lt;p&gt;A decade ago the argument was settled in the hallway: &lt;strong&gt;mobile first&lt;/strong&gt;. If the product did not work on a phone, it did not work.&lt;/p&gt;
&lt;p&gt;Teams stopped designing for a 27-inch monitor and shrinking later. They started with the constrained surface and let the desktop inherit the discipline.&lt;/p&gt;
&lt;p&gt;That constraint was a screen.&lt;/p&gt;
&lt;p&gt;Today the constraint is a &lt;strong&gt;capability contract&lt;/strong&gt;. Users still want a UI, but more and more of the real work is asked in chat: Claude, Cursor, Grok Bot, an in-product agent.&lt;/p&gt;
&lt;p&gt;They do not want another settings page. They want to say what they need and have it done. Docs, support tickets, and click-paths become the fallback when the product cannot be &lt;em&gt;operated&lt;/em&gt; by an agent.&lt;/p&gt;
&lt;p&gt;So the slogan flips: &lt;strong&gt;MCP first&lt;/strong&gt;, or more precisely, &lt;strong&gt;agent first / skills first&lt;/strong&gt;. Ship the tools, permissions, and judgment an agent needs &lt;em&gt;before&lt;/em&gt; you polish the human interface that wraps them.&lt;/p&gt;
&lt;p&gt;I am not arguing that MCP replaces your API. I already wrote &lt;a href=&quot;https://ansezz.com/blog/api-vs-mcp/&quot;&gt;API vs MCP&lt;/a&gt; for that fork.&lt;/p&gt;
&lt;p&gt;MCP is how agents &lt;em&gt;discover and call&lt;/em&gt; capabilities. Skills are how they apply judgment. The UI is how humans supervise. Get the order wrong and you bolt a chatbot onto a product that was never operable. Agents also need a map of what to read, and an &lt;a href=&quot;https://ansezz.com/tools/llms-txt-generator/&quot;&gt;llms.txt file&lt;/a&gt; at your site root is the simplest one to publish.&lt;/p&gt;
&lt;h2&gt;What &quot;MCP first&quot; actually means&lt;/h2&gt;
&lt;p&gt;MCP first does &lt;strong&gt;not&lt;/strong&gt; mean &quot;add a Model Context Protocol server and call it a day.&quot;&lt;/p&gt;
&lt;p&gt;It means you design the product as a set of &lt;strong&gt;outcomes an agent can complete&lt;/strong&gt;, with:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Named tools:&lt;/strong&gt; create invoice, list delayed orders, refund within policy, rotate a key.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Clear inputs and outputs:&lt;/strong&gt; schemas the model can fill without guessing.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Permissions:&lt;/strong&gt; who the actor is, which tenant, which scopes (&lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;auth and audit&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Safe mutation rules:&lt;/strong&gt; idempotency, rate limits, structured errors (&lt;a href=&quot;https://ansezz.com/blog/mcp-idempotency-laravel-mutations/&quot;&gt;idempotency&lt;/a&gt;, &lt;a href=&quot;https://ansezz.com/blog/mcp-structured-tool-errors-laravel/&quot;&gt;tool errors&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Skills:&lt;/strong&gt; playbooks and guardrails so the agent knows &lt;em&gt;when&lt;/em&gt; to call which tool, not just &lt;em&gt;that&lt;/em&gt; a tool exists.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;A human UI that consumes the same capabilities:&lt;/strong&gt; screens become views and approvals over the same contract, not a parallel codebase.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Mobile first forced responsive layout. MCP first forces &lt;strong&gt;operable capability&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;If an agent with the right credentials cannot complete the job end-to-end, the product is not finished, no matter how pretty the dashboard is.&lt;/p&gt;
&lt;h2&gt;The two-customer problem&lt;/h2&gt;
&lt;figure&gt;
&lt;p&gt;Every serious product now has &lt;strong&gt;two customers&lt;/strong&gt;:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Customer&lt;/th&gt;
&lt;th&gt;What they need&lt;/th&gt;
&lt;th&gt;Failure mode&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Human&lt;/td&gt;
&lt;td&gt;Screens, copy, empty states, accessibility&lt;/td&gt;
&lt;td&gt;Confusing UI; they open a ticket&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Agent&lt;/td&gt;
&lt;td&gt;Tools, schemas, errors they can recover from, audit trails&lt;/td&gt;
&lt;td&gt;Silent failure; retries; invented actions&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Most teams still ship for the human and hope the agent can scrape the DOM or call undocumented REST. That is the 2012 equivalent of &quot;we&apos;ll make the mobile site later.&quot;&lt;/p&gt;
&lt;p&gt;The fix is one capability layer. Humans get forms and tables. Agents get MCP (or an equivalent tool surface). Both hit the same domain services.&lt;/p&gt;
&lt;p&gt;When you add &quot;export CSV,&quot; you add the tool &lt;em&gt;and&lt;/em&gt; the button, not only the button.&lt;/p&gt;

Next time you add a button, write the matching tool in the same pull request, calling the same domain service.

&lt;h2&gt;Reverse the build sequence&lt;/h2&gt;

  &lt;div&gt;screens → API → maybe docs → maybe &quot;AI feature&quot;&lt;/div&gt;
  &lt;div&gt;outcomes → tools → permissions → skills → API/CLI → UI&lt;/div&gt;

&lt;p&gt;Concrete example: an ops tool for delayed Shopify orders.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Outcome:&lt;/strong&gt; &quot;Find delayed orders for this shop and propose a next action within policy.&quot;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tools:&lt;/strong&gt; &lt;code&gt;list_delayed_orders&lt;/code&gt;, &lt;code&gt;get_order&lt;/code&gt;, &lt;code&gt;create_customer_message&lt;/code&gt;, &lt;code&gt;issue_partial_refund&lt;/code&gt; (scoped).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Permissions:&lt;/strong&gt; shop actor, refund ceiling, PII redaction in logs.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Skills:&lt;/strong&gt; when to refund vs reship vs escalate; never invent tracking numbers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;API:&lt;/strong&gt; the same mutations your admin already uses.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;UI:&lt;/strong&gt; a queue page and an approval modal that call the &lt;em&gt;same&lt;/em&gt; services.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If you start with the queue page, the agent becomes a second-class citizen forever. If you start with the tools, the queue page is just one client.&lt;/p&gt;
&lt;h2&gt;Chat is a front door, not the product&lt;/h2&gt;
&lt;figure&gt;
&lt;p&gt;People reach for chat because self-service still fails often enough to hurt. Industry surveys have long shown most customers try to solve a problem themselves before they contact a human, often cited around four in five attempts.&lt;/p&gt;
&lt;p&gt;Completion is the hard part. When the product cannot be operated by an agent with tools, chat becomes theater: a polite model that cannot refund, cannot look up the right tenant, and cannot tell you why the tool failed.&lt;/p&gt;
&lt;p&gt;Treat chat as a &lt;strong&gt;front door&lt;/strong&gt;:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Behind it: MCP tools (or skills that wrap them).&lt;/li&gt;
&lt;li&gt;Beside it: approval gates for irreversible money/PII moves.&lt;/li&gt;
&lt;li&gt;Under it: audit logs you would show a security reviewer.&lt;/li&gt;
&lt;li&gt;Past it: human support when the agent correctly escalates.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;No more &quot;read the docs, click twelve pages, then open a ticket.&quot; The docs become training data for skills. The pages become optional. Support becomes the exception path.&lt;/p&gt;
&lt;h2&gt;Skills first, not prompt first&lt;/h2&gt;
&lt;p&gt;A tool without a skill is a loaded gun with no safety briefing.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Skills&lt;/strong&gt; (playbooks, runbooks, Cursor-style skill files, Claude Projects instructions; pick your stack) encode:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;which tools exist for this job&lt;/li&gt;
&lt;li&gt;sequencing and stop conditions&lt;/li&gt;
&lt;li&gt;what &quot;done&quot; looks like&lt;/li&gt;
&lt;li&gt;when to ask the human&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;MCP first without skills first produces agents that call &lt;code&gt;refund_order&lt;/code&gt; because the user sounded upset. Skills first without MCP first produces beautiful instructions with nothing to execute.&lt;/p&gt;
&lt;p&gt;Ship both. In practice I write the skill outline in the same PR as the first tool handlers: same review, same tenant tests.&lt;/p&gt;
&lt;h2&gt;What this is not&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Not&lt;/strong&gt; &quot;delete the UI.&quot; Humans still approve, explore, and debug. Agent-first products often need &lt;em&gt;better&lt;/em&gt; UIs for supervision.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not&lt;/strong&gt; &quot;every CRUD app needs a public MCP server tomorrow.&quot; Internal agent access (Cursor, Claude Desktop, your own bot) is enough to force the discipline. Public MCP is a distribution choice.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not&lt;/strong&gt; &quot;skip the API.&quot; MCP sits on capabilities. Thin, boring domain services still win.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not&lt;/strong&gt; &quot;let the model invent side effects.&quot; Auth, idempotency, structured errors, and rate limits are the mobile viewport of this era: constraints that make the product honest. That is why I shipped the &lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;Laravel MCP safety trilogy&lt;/a&gt; before preaching the slogan.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;A one-sprint checklist&lt;/h2&gt;
&lt;p&gt;If you already have a product, you do not need a rewrite. In one sprint:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Pick &lt;strong&gt;three&lt;/strong&gt; high-value outcomes users already ask support for.&lt;/li&gt;
&lt;li&gt;Expose each as a tool with a schema, actor, and audit line.&lt;/li&gt;
&lt;li&gt;Return &lt;strong&gt;recoverable&lt;/strong&gt; failures (&lt;code&gt;not_found&lt;/code&gt;, &lt;code&gt;forbidden&lt;/code&gt;, &lt;code&gt;validation_failed&lt;/code&gt;) instead of empty 500s.&lt;/li&gt;
&lt;li&gt;Wrap mutations in idempotency keys.&lt;/li&gt;
&lt;li&gt;Write a short skill that sequences those tools and names the escalate path.&lt;/li&gt;
&lt;li&gt;Point your internal agent (Claude / Cursor / your bot) at it and dogfood for a week.&lt;/li&gt;
&lt;li&gt;Only then decide whether the human UI needs a new screen, or just a better approval affordance on top of what the agent already uses.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If the agent cannot finish the job with a human in the loop for money moves, you learned something cheap. If it can, you just shipped mobile-first for the agent decade.&lt;/p&gt;

Open your last month of support tickets and pick the three requests that come up most. Those are your first three tools.

&lt;h2&gt;The hardest constraint first&lt;/h2&gt;
&lt;p&gt;Mobile first was never really about phones. It was about designing for the &lt;strong&gt;hardest real constraint&lt;/strong&gt; first.&lt;/p&gt;
&lt;p&gt;The hard constraint now is: &lt;em&gt;can an authorized agent complete the work safely, with skills and tools, while a human supervises?&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Call it MCP first, agent first, or skills first; same idea. Prepare the tools and access. Then build the product. Chat becomes the place people ask; capability is what answers.&lt;/p&gt;
&lt;p&gt;If you are wiring this into multi-tenant Laravel, start with &lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;auth and audit&lt;/a&gt;, &lt;a href=&quot;https://ansezz.com/blog/mcp-idempotency-laravel-mutations/&quot;&gt;idempotency&lt;/a&gt;, and &lt;a href=&quot;https://ansezz.com/blog/mcp-structured-tool-errors-laravel/&quot;&gt;structured tool errors&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If you are still choosing the connector shape, read &lt;a href=&quot;https://ansezz.com/blog/api-vs-mcp/&quot;&gt;API vs MCP&lt;/a&gt; first.&lt;/p&gt;

- Every product now has two customers: a human and an agent.
- Build in this order: outcomes, tools, permissions, skills, API, then UI.
- Chat is a front door. Tools, approval gates and audit logs do the work behind it.
- Ship skills with tools, so the agent knows when to call what.

&lt;p&gt;Which three things do your users ask support for that an agent with the right tools could finish today?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>mcp</category><category>architecture</category><category>agentic-ai</category><category>api-design</category><category>ai</category><category>claude</category></item><item><title>MCP vs A2A vs ACP: the agent protocol stack</title><link>https://ansezz.com/blog/mcp-vs-a2a-vs-acp/</link><guid isPermaLink="true">https://ansezz.com/blog/mcp-vs-a2a-vs-acp/</guid><description>MCP connects agents to tools, A2A connects agents to each other, and ACP has folded into A2A. How the two-layer agent protocol stack fits together in 2026.</description><pubDate>Wed, 05 Aug 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;The missing piece in most multi-agent systems is not model quality. It is a communication standard.&lt;/p&gt;

- MCP connects agents to tools and data. A2A connects agents to each other.
- ACP, the third name you will see in older posts, has merged into A2A.
- Most agents play both roles at once: they use tools over MCP and answer peers over A2A.

&lt;p&gt;You are ready to move past single-prompt chatbots and build a real multi-agent system. Then you look at what you actually have: agents that cannot reach your Postgres database without a bespoke script, and cannot coordinate with the agent another team shipped last quarter without a shared Slack channel and a human in the middle.&lt;/p&gt;
&lt;p&gt;Without a shared standard, you spend most of your engineering time writing glue code for integrations and very little on the behavior that makes the agents worth running. Every schema change breaks a hand-rolled adapter somewhere.&lt;/p&gt;
&lt;p&gt;The good news is that the landscape has converged. Two protocols now cover the two axes that matter: the Model Context Protocol (MCP) and Agent2Agent (A2A). The Agent Communication Protocol (ACP) has been folded into A2A.&lt;/p&gt;
&lt;p&gt;This post breaks down what each layer does and how to wire them together.&lt;/p&gt;
&lt;h2&gt;The current state of agent protocols&lt;/h2&gt;
&lt;p&gt;In early 2025 you had to pick a vendor SDK and live with it. Function calling looked different on every model, and agent frameworks each invented their own message envelope. Two things changed that.&lt;/p&gt;
&lt;p&gt;First, Anthropic donated MCP to the Linux Foundation, where it now sits under the Agentic AI Foundation (AAIF) alongside other agentic projects. Second, Google donated A2A to the Linux Foundation in mid-2025.&lt;/p&gt;
&lt;p&gt;Both protocols are now governed in the open by the same umbrella, which is the main reason the stack finally stopped moving under everyone&apos;s feet.&lt;/p&gt;
&lt;h3&gt;Vertical and horizontal&lt;/h3&gt;
&lt;p&gt;The second shift is architectural. You no longer need one protocol that does everything. You use a &lt;strong&gt;vertical&lt;/strong&gt; protocol for reaching data and tools, and a &lt;strong&gt;horizontal&lt;/strong&gt; protocol for agents talking to peers.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Protocol&lt;/th&gt;
&lt;th&gt;Primary role&lt;/th&gt;
&lt;th&gt;Governance&lt;/th&gt;
&lt;th&gt;Status&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;MCP&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Agent to tool/data&lt;/td&gt;
&lt;td&gt;Linux Foundation, AAIF&lt;/td&gt;
&lt;td&gt;De-facto standard&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;A2A&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Agent to agent&lt;/td&gt;
&lt;td&gt;Linux Foundation&lt;/td&gt;
&lt;td&gt;Stable, actively spec&apos;d&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;ACP&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Agent messaging&lt;/td&gt;
&lt;td&gt;Legacy (IBM / BeeAI)&lt;/td&gt;
&lt;td&gt;Merged into A2A&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;MCP: the universal adapter for tools&lt;/h2&gt;
&lt;p&gt;MCP is the vertical layer. It standardizes how an agent connects to everything that is &lt;em&gt;not&lt;/em&gt; another agent: your Shopify store, your Postgres instance, a filesystem, an internal REST service.&lt;/p&gt;

  &lt;div&gt;A filesystem tool definition written for one specific model&apos;s function-calling format.&lt;/div&gt;
  &lt;div&gt;One server. Any MCP-compatible client connects and discovers the same capabilities.&lt;/div&gt;

&lt;p&gt;Any MCP-compatible client (Claude, an IDE assistant, a local model runner) connects and discovers the same capabilities without you rewriting anything.&lt;/p&gt;
&lt;figure&gt;
&lt;p&gt;&lt;strong&gt;Why MCP won the tool layer:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;JSON-RPC 2.0 on the wire.&lt;/strong&gt; Boring, well-understood, easy to debug.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Transport flexibility.&lt;/strong&gt; &lt;code&gt;stdio&lt;/code&gt; for local servers, Streamable HTTP for remote ones. (The older HTTP+SSE transport is legacy; new remote servers should use Streamable HTTP.)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Three primitives, not thirty.&lt;/strong&gt; Servers expose tools the model can call, resources it can read, and prompts the user can invoke. Clients contribute sampling and roots, and a 2025 revision added elicitation so a server can ask the user for missing input mid-call.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Real ecosystem.&lt;/strong&gt; Thousands of public servers exist for common SaaS platforms, and the official MCP Registry gives clients a discovery path instead of a README scavenger hunt.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Scoped permissions.&lt;/strong&gt; Servers expose only what you register, so an agent sees the slice of data it needs and nothing else.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If you are modernizing how your systems are consumed, exposing your data through MCP is the first move with the biggest payoff. It decouples your tools from your model choice, which is the coupling that hurts most when you swap models.&lt;/p&gt;
&lt;p&gt;I went deeper on the mechanics in &lt;a href=&quot;https://ansezz.com/blog/api-vs-mcp/&quot;&gt;API vs MCP&lt;/a&gt; and &lt;a href=&quot;https://ansezz.com/blog/mcp-context-aware-agents/&quot;&gt;MCP tool-use for context-aware agents&lt;/a&gt;.&lt;/p&gt;

Pick one internal API your agents already call through a custom script and wrap it in an MCP server.

&lt;h2&gt;A2A: the social fabric for agents&lt;/h2&gt;
&lt;p&gt;MCP handles tools. A2A handles peers.&lt;/p&gt;
&lt;p&gt;When your merchandising agent needs stock levels from an inventory agent owned by another team (one built on a different framework, deployed in a different cluster), that conversation is A2A. This is the horizontal layer.&lt;/p&gt;
&lt;p&gt;A2A lets agents discover each other, delegate tasks, stream progress, and hand back results.&lt;/p&gt;
&lt;h3&gt;The Agent Card&lt;/h3&gt;
&lt;p&gt;The anchor of the protocol is the &lt;strong&gt;Agent Card&lt;/strong&gt;: a JSON document, conventionally served at &lt;code&gt;/.well-known/agent-card.json&lt;/code&gt;. It declares who the agent is, which skills it offers, which transports and auth schemes it supports, and what input and output types it accepts. Discovery is fetching that file.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What A2A gives you:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Capability discovery.&lt;/strong&gt; A client reads an Agent Card (or queries a registry) to find an agent that handles the job, instead of hard-coding a hostname.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Task delegation with a real lifecycle.&lt;/strong&gt; Tasks move through explicit states (submitted, working, input-required, completed, failed, canceled), so a caller can reason about a long-running job rather than polling a black box.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Streaming and callbacks.&lt;/strong&gt; Server-Sent Events for live progress on an open connection, plus webhook-style push notifications for tasks that outlive it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Framework independence.&lt;/strong&gt; The peer on the other side can be LangGraph, CrewAI, a Laravel service wrapping a model, or something homegrown. The wire format is what you agree on, not the runtime.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Standard auth.&lt;/strong&gt; Agent Cards declare security schemes, so you authenticate agent-to-agent traffic with the same primitives you already use for APIs.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is what makes cross-team agents workable. Building &lt;a href=&quot;https://ansezz.com/blog/agentic-commerce-shopify/&quot;&gt;agentic commerce on Shopify&lt;/a&gt; already means a checkout flow handing structured instructions to fulfillment logic; A2A is what stops that handoff from being a private contract nobody else can reuse.&lt;/p&gt;
&lt;h2&gt;Why ACP merged into A2A&lt;/h2&gt;
&lt;p&gt;You will still hit references to the Agent Communication Protocol. ACP came out of IBM and the BeeAI team as a REST-native approach to agent messaging.&lt;/p&gt;
&lt;p&gt;It was good at exactly the thing A2A was weakest at early on: stateful, long-running, asynchronous work.&lt;/p&gt;
&lt;p&gt;The problem was arithmetic. Two competing agent-to-agent protocols meant every framework author had to pick one or implement both, which is how ecosystems stall. During 2025 the ACP maintainers moved to consolidate behind A2A under Linux Foundation governance.&lt;/p&gt;
&lt;p&gt;The practical consequence is short. ACP is no longer an architectural choice you need to evaluate. Its strong ideas around state management and durable messaging live on in A2A&apos;s task model.&lt;/p&gt;
&lt;p&gt;If you had ACP on a roadmap, substitute A2A. The concepts map closely and the community is now in one place.&lt;/p&gt;
&lt;h2&gt;Architecting the two-layer stack&lt;/h2&gt;
&lt;p&gt;The mental model that keeps this straight:&lt;/p&gt;
&lt;p&gt;MCP is the device driver, A2A is the network protocol.&lt;/p&gt;
&lt;p&gt;One lets a process talk to the hardware it is attached to; the other lets it talk to other machines. You need both, and they do not overlap.&lt;/p&gt;
&lt;p&gt;An agent is typically an A2A &lt;strong&gt;server&lt;/strong&gt; to its peers and an MCP &lt;strong&gt;client&lt;/strong&gt; to its tools, at the same time. That dual role is the whole architecture.&lt;/p&gt;
&lt;figure&gt;
&lt;p&gt;&lt;strong&gt;A workable implementation order:&lt;/strong&gt;&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Data layer (MCP).&lt;/strong&gt; Wrap your internal APIs and databases in MCP servers. This is the step that pays off immediately, even with a single agent, and it is where a lot of &lt;a href=&quot;https://ansezz.com/blog/claude-mcp-dev-tools/&quot;&gt;Claude and MCP dev tooling&lt;/a&gt; already lives.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Coordination layer (A2A).&lt;/strong&gt; Put an A2A-compliant interface in front of each agent and publish its Agent Card. This is how &lt;a href=&quot;https://ansezz.com/blog/agentic-workflows-vibe-coding/&quot;&gt;informal agentic workflows&lt;/a&gt; graduate into services other teams can call.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Governance layer.&lt;/strong&gt; Route the traffic through an &lt;a href=&quot;https://ansezz.com/blog/api-gateway-ai-stack/&quot;&gt;AI gateway&lt;/a&gt; so you get auth, rate limits, cost attribution, and traces on both protocols instead of guessing where the spend went.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Tools and peers are not interchangeable&lt;/h3&gt;
&lt;p&gt;A tool call and an agent delegation are not interchangeable, even when both are technically reachable.&lt;/p&gt;
&lt;p&gt;Exposing another team&apos;s agent as an MCP tool flattens away the task lifecycle and turns a long-running negotiation into a request that either returns or times out.&lt;/p&gt;
&lt;p&gt;Use MCP for deterministic capabilities you own, and A2A when the other side needs to reason, ask you a follow-up question, or take twenty minutes.&lt;/p&gt;
&lt;h2&gt;Practical implementation tips&lt;/h2&gt;
&lt;p&gt;Moving to a protocol-first architecture is mostly a change in what you consider the unit of work. Stop shipping &quot;an agent&quot; and start shipping services that speak these standards.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Audit your tools first.&lt;/strong&gt; Pick the five tools your agents actually reach for and build or adopt MCP servers for them. Resist wrapping everything: an agent handed forty tools makes worse choices than one handed six.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Write Agent Cards early.&lt;/strong&gt; Even with two agents, defining the card forces you to name each agent&apos;s skills and boundaries. Most multi-agent designs fail because responsibilities overlap, and the card is where that shows up before it becomes a runtime problem.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Standardize transports.&lt;/strong&gt; Streamable HTTP for remote MCP servers, HTTP with SSE for A2A streaming. Streaming matters more than it looks: without it you cannot see intermediate reasoning or partial tool output, and debugging a multi-agent failure becomes archaeology.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Version the contracts, not the prompts.&lt;/strong&gt; Agent Cards and tool schemas are public interfaces now. Treat a changed tool signature like a breaking API change, because for every agent calling it, that is exactly what it is.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Instrument at the boundary.&lt;/strong&gt; Every MCP call and A2A task should emit a trace with a correlation ID that survives delegation. When a five-agent chain returns nonsense, the only cheap way to find the bad hop is a trace that spans all of them.&lt;/p&gt;

Write an Agent Card for one agent you already run, even if nobody calls it yet. Naming its skills will show you where responsibilities overlap.

&lt;p&gt;If you are wiring MCP and A2A into a real product, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams ship it&lt;/a&gt;.&lt;/p&gt;

- **MCP is vertical.** It connects agents to tools, databases, and APIs, and it is the de-facto standard for that layer.
- **A2A is horizontal.** It handles discovery, delegation, and task lifecycle between agents, across frameworks and teams.
- **ACP is legacy.** It merged into A2A. Do not start new work on standalone ACP.
- **Governance is settled.** Both protocols now sit under Linux Foundation stewardship, which is what makes them safe to build against.
- **Each agent plays two roles.** A2A server to its peers, MCP client to its tools: that dual role is the stack in one sentence.
- **The boundary matters.** Deterministic capability you own is a tool; another team&apos;s reasoning system is a peer. Mixing them up is how the architecture rots.

&lt;p&gt;How are you handling coordination between agent frameworks in your production stack right now?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>mcp</category><category>agentic-ai</category><category>ai</category><category>architecture</category></item><item><title>Modular monoliths first: why microservices can wait</title><link>https://ansezz.com/blog/modular-monolith-first/</link><guid isPermaLink="true">https://ansezz.com/blog/modular-monolith-first/</guid><description>Distributed systems are the priciest fix for a problem you don&apos;t have. How to build a modular monolith, own data per module, and know when to split.</description><pubDate>Wed, 24 Jun 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Distributed systems are the most expensive way to solve a problem you do not have yet.&lt;/p&gt;

- Start with one deployable app split into strict modules with contracts, private data and internal events.
- Enforce module boundaries with architecture tests in CI, and never let modules share tables or JOINs.
- Split only on real friction: team bottlenecks, divergent scaling needs or repeat fault cascades. Extract workers first.

&lt;p&gt;Every year a new batch of SaaS founders jumps straight to microservices because they want to &quot;build for scale.&quot;&lt;/p&gt;
&lt;p&gt;Six months later they are debugging network latency and distributed transactions instead of shipping features. The product has not moved. The infrastructure bill has.&lt;/p&gt;
&lt;p&gt;The modular monolith has quietly won this argument. It gives you the logical separation you actually need without the operational tax of a distributed environment.&lt;/p&gt;
&lt;p&gt;This post covers why you should start there, how to structure it so it stays modular, and the specific signals that tell you it is finally time to split.&lt;/p&gt;
&lt;p&gt;If you are still weighing the two patterns at a high level, read &lt;a href=&quot;https://ansezz.com/blog/monolith-vs-microservices/&quot;&gt;monolith vs microservices&lt;/a&gt; first. This post assumes you have picked the monolith and want to build one that does not rot.&lt;/p&gt;
&lt;h2&gt;The microservice tax is real&lt;/h2&gt;
&lt;p&gt;Most startups choose microservices for the wrong reasons. They look at Netflix or Uber and assume the infrastructure is the blueprint for success.&lt;/p&gt;
&lt;p&gt;What they miss is that those companies adopted microservices to solve &lt;strong&gt;organizational&lt;/strong&gt; problems (hundreds of engineers who could not coordinate a single deploy), not purely technical ones.&lt;/p&gt;
&lt;p&gt;Split prematurely and you pay a heavy tax:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Operational overhead.&lt;/strong&gt; You now need service discovery, centralized logging, distributed tracing, and a CI/CD pipeline per repository. None of that ships a feature.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Data consistency.&lt;/strong&gt; Distributed transactions are hard. You end up with eventual consistency problems that need sagas or an outbox pattern to fix: code that exists only because you split.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Network latency.&lt;/strong&gt; Every cross-service call costs milliseconds and can fail. In a monolith these are function calls in memory that cannot time out.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Developer friction.&lt;/strong&gt; Debugging a request that hops through five services is far worse than stepping through one process. Reproducing it locally is worse still.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;For a small team this overhead kills velocity. You spend 40% of your time on infrastructure and 60% on product. In a modular monolith that ratio flips back toward the thing customers pay for.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;What a modular monolith actually is&lt;/h2&gt;
&lt;p&gt;A modular monolith is not a big ball of mud with nicer folder names. It is a &lt;strong&gt;single deployable unit&lt;/strong&gt; where code is strictly organized into independent modules with well-defined interfaces between them.&lt;/p&gt;
&lt;p&gt;In a &lt;a href=&quot;https://ansezz.com/blog/category/laravel/&quot;&gt;Laravel&lt;/a&gt; codebase that means each domain gets its own namespace, its own service provider, its own routes, and its own migrations.&lt;/p&gt;
&lt;p&gt;A &lt;code&gt;Billing&lt;/code&gt; module never reaches into the &lt;code&gt;Users&lt;/code&gt; tables directly. It talks through a contract.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// app/Modules/Billing/Contracts/CustomerDirectory.php
namespace App\Modules\Billing\Contracts;

interface CustomerDirectory
{
    public function find(int $customerId): ?CustomerSummary;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;code&gt;// app/Modules/Users/Adapters/EloquentCustomerDirectory.php
namespace App\Modules\Users\Adapters;

use App\Modules\Billing\Contracts\CustomerDirectory;
use App\Modules\Billing\Contracts\CustomerSummary;
use App\Modules\Users\Models\User;

final class EloquentCustomerDirectory implements CustomerDirectory
{
    public function find(int $customerId): ?CustomerSummary
    {
        $user = User::query()-&amp;gt;find($customerId);

        return $user
            ? new CustomerSummary($user-&amp;gt;id, $user-&amp;gt;email, $user-&amp;gt;billing_country)
            : null;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;Billing&lt;/code&gt; depends on an interface it owns and a DTO it controls. &lt;code&gt;Users&lt;/code&gt; supplies the implementation. Swap that adapter for an HTTP client tomorrow and &lt;code&gt;Billing&lt;/code&gt; does not change a single line.&lt;/p&gt;
&lt;p&gt;The seam already exists. You just move what is behind it.&lt;/p&gt;
&lt;p&gt;The goal is &lt;strong&gt;logical separation with physical unity&lt;/strong&gt;. You get a clean, decoupled &lt;a href=&quot;https://ansezz.com/blog/category/architecture/&quot;&gt;architecture&lt;/a&gt; without managing a fleet of containers on &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;Coolify&lt;/a&gt; or Kubernetes before you need to.&lt;/p&gt;
&lt;h2&gt;Bounded contexts keep the modules honest&lt;/h2&gt;
&lt;p&gt;The concept doing the real work here is the &lt;strong&gt;bounded context&lt;/strong&gt;, a term from Domain-Driven Design that marks the boundary where one model of a thing applies.&lt;/p&gt;
&lt;p&gt;A &lt;code&gt;Product&lt;/code&gt; in the &lt;code&gt;Inventory&lt;/code&gt; module is not the same object as a &lt;code&gt;Product&lt;/code&gt; in the &lt;code&gt;Marketing&lt;/code&gt; module. One cares about stock levels, SKUs, and warehouse locations. The other cares about SEO titles, hero images, and merchandising rules.&lt;/p&gt;
&lt;p&gt;Forcing them into one bloated &lt;code&gt;Product&lt;/code&gt; model is how modular monoliths turn into mud.&lt;/p&gt;
&lt;p&gt;Three rules keep boundaries intact:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Enforce them mechanically.&lt;/strong&gt; Human discipline fails under deadline. Add an architecture test that fails the build when &lt;code&gt;Modules\Billing&lt;/code&gt; imports &lt;code&gt;Modules\Inventory\Models&lt;/code&gt;. In PHP, &lt;a href=&quot;https://github.com/opensoftwareconsulting/deptrac&quot;&gt;Deptrac&lt;/a&gt; or a Pest arch test does this in a few lines. Any language has an equivalent.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Keep the shared kernel tiny.&lt;/strong&gt; A little shared code is fine. A giant &lt;code&gt;Common&lt;/code&gt; package that every module depends on is a monolith wearing a costume; you can never split anything out of it.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Prefer events over direct calls.&lt;/strong&gt; When &lt;code&gt;Orders&lt;/code&gt; needs &lt;code&gt;Shipping&lt;/code&gt; to react, emit a domain event instead of calling a method. Replacing an in-process listener with a message queue later becomes a config change, not a rewrite.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That third rule pays off the most. Internal events are the cheapest dress rehearsal for &lt;a href=&quot;https://ansezz.com/blog/synchronous-vs-asynchronous-communication/&quot;&gt;asynchronous communication&lt;/a&gt; you will ever get, and they cost nothing while everything still runs in one process.&lt;/p&gt;

Add one architecture test today that fails when any module imports another module&apos;s `Models` namespace. Run it and count the failures.

&lt;h2&gt;The data ownership trap&lt;/h2&gt;
&lt;p&gt;The database is where most monolith-to-microservice migrations die.&lt;/p&gt;
&lt;p&gt;If your modules share tables or run JOINs across domains, you are coupled at the data layer, the hardest coupling to break. No amount of tidy namespaces saves you when &lt;code&gt;Reporting&lt;/code&gt; joins six tables owned by four other modules.&lt;/p&gt;
&lt;p&gt;So aim for &lt;strong&gt;schema per module&lt;/strong&gt;. Use one physical Postgres or MySQL instance for simplicity, but give each module its own tables and treat them as private. In practice:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;No foreign keys crossing module boundaries. Store the ID and let the application layer resolve the relationship.&lt;/li&gt;
&lt;li&gt;No cross-module JOINs. If &lt;code&gt;Billing&lt;/code&gt; needs a customer email, it calls the contract, not the &lt;code&gt;users&lt;/code&gt; table.&lt;/li&gt;
&lt;li&gt;Read models over reach-ins. If &lt;code&gt;Reporting&lt;/code&gt; needs a wide view, have modules publish into a reporting table they explicitly own.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Here is the test: &lt;strong&gt;if you cannot imagine running your &lt;code&gt;Orders&lt;/code&gt; module against a separate database server tomorrow, your monolith is not modular yet.&lt;/strong&gt; It is a monolith with folders.&lt;/p&gt;

  &lt;div&gt;Foreign keys across modules, `Reporting` joining six tables owned by four other modules, `Billing` reading the `users` table.&lt;/div&gt;
  &lt;div&gt;Schema per module, IDs instead of cross-module foreign keys, contracts instead of JOINs, read models each module publishes.&lt;/div&gt;

&lt;h2&gt;A decision framework for when to split&lt;/h2&gt;
&lt;p&gt;You rarely outgrow a monolith because of traffic. A single well-tuned Laravel box with &lt;a href=&quot;https://ansezz.com/blog/laravel-octane-high-traffic/&quot;&gt;Octane&lt;/a&gt; and a queue handles more load than most SaaS companies ever see.&lt;/p&gt;
&lt;p&gt;You outgrow it because of &lt;strong&gt;friction&lt;/strong&gt;. Three signals matter:&lt;/p&gt;
&lt;h3&gt;1. Team autonomy&lt;/h3&gt;
&lt;p&gt;Are developers constantly blocking each other? Twenty engineers merging into one codebase with a deployment queue is a real organizational bottleneck, and that alone can justify a split.&lt;/p&gt;
&lt;p&gt;Five engineers? A monolith is almost always faster. Conway&apos;s Law cuts both ways: do not buy a distributed architecture for a co-located team.&lt;/p&gt;
&lt;h3&gt;2. Divergent scaling profiles&lt;/h3&gt;
&lt;p&gt;Does one part of the app have radically different resource needs? An AI inference module that wants GPUs while your dashboard is plain CRUD is a real case for extraction.&lt;/p&gt;
&lt;p&gt;You stop paying for GPU-sized instances to serve settings pages, and your &lt;a href=&quot;https://ansezz.com/blog/category/devops/&quot;&gt;DevOps&lt;/a&gt; spend tracks actual demand.&lt;/p&gt;
&lt;h3&gt;3. Fault isolation&lt;/h3&gt;
&lt;p&gt;If a bug in non-critical reporting takes down checkout, you have a resilience problem. First try to solve it in-process: better error handling, background jobs, timeouts, a bulkhead around the risky call.&lt;/p&gt;
&lt;p&gt;If it keeps happening, a separate service acts as a circuit breaker around your core revenue path.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Metric&lt;/th&gt;
&lt;th&gt;Modular monolith&lt;/th&gt;
&lt;th&gt;Microservices&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Deployment&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Simple (one pipeline)&lt;/td&gt;
&lt;td&gt;Complex (many pipelines)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Testing&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Easy (in-process)&lt;/td&gt;
&lt;td&gt;Hard (end-to-end focused)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Data integrity&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Strong (ACID)&lt;/td&gt;
&lt;td&gt;Eventual consistency&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Debugging&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Stack trace&lt;/td&gt;
&lt;td&gt;Distributed trace&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Operational cost&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Low&lt;/td&gt;
&lt;td&gt;High&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Team scaling&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Bottlenecks past ~15 to 20&lt;/td&gt;
&lt;td&gt;Scales with squads&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Notice what is missing: raw performance. It is almost never the deciding factor, and when it is, a bigger box or a read replica usually beats a rewrite.&lt;/p&gt;
&lt;h2&gt;Extract background workers before services&lt;/h2&gt;
&lt;p&gt;When the split finally makes sense, your first move should not be a full service.&lt;/p&gt;
&lt;p&gt;Start with an &lt;strong&gt;extracted background worker&lt;/strong&gt;. Move heavy, long-running tasks (PDF generation, CSV exports, video transcoding, embedding jobs) into their own process consuming from a queue.&lt;/p&gt;
&lt;p&gt;You get isolation, independent scaling, and blast-radius reduction without the pain of synchronous API contracts, retries, and versioning.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://ansezz.com/blog/scaling-with-rabbitmq/&quot;&gt;RabbitMQ&lt;/a&gt; or a &lt;a href=&quot;https://ansezz.com/blog/event-driven-pubsub/&quot;&gt;Pub/Sub-style event backbone&lt;/a&gt; covers most of this, and the same pattern powers &lt;a href=&quot;https://ansezz.com/blog/message-queues-document-processing/&quot;&gt;queue-based document processing&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Only after that should you consider carving out a synchronous service. When you do, the &lt;a href=&quot;https://ansezz.com/blog/monolith-to-microservices/&quot;&gt;strangler fig migration&lt;/a&gt; is the safe path: route one endpoint at a time and keep the monolith as your fallback.&lt;/p&gt;
&lt;figure&gt;
&lt;h3&gt;Wait until the domain is stable&lt;/h3&gt;
&lt;p&gt;One more constraint: &lt;strong&gt;wait until your domain is stable&lt;/strong&gt;. Early-stage products change their data models weekly.&lt;/p&gt;
&lt;p&gt;Hard service boundaries during that discovery phase turn every small feature into a multi-service orchestration project. Boundaries are cheap to move inside a monolith and expensive to move across a network.&lt;/p&gt;

- **Start modular.** Separate business domains with namespaces, modules, and contracts from day one. This costs nothing early and is nearly impossible to retrofit later.
- **Enforce boundaries with tooling.** Architecture tests in CI, not code-review vigilance.
- **Own your data per module.** No cross-module foreign keys, no cross-domain JOINs. Data coupling is the coupling that traps you.
- **Emit events internally.** In-process listeners today become queue consumers tomorrow with a config change.
- **Split on friction, not fashion.** Deployment bottlenecks, divergent scaling profiles, and repeat fault cascades are reasons. A conference talk is not.
- **Extract workers first.** Async background processes give you most of the isolation benefits at a fraction of the operational cost.

&lt;p&gt;If your architecture lets you change your mind later without a rewrite, you have already won. That is the whole point of deferring the decision.&lt;/p&gt;
&lt;p&gt;How often are you actually checking for cross-module coupling in your codebase? If the answer is &quot;never,&quot; that is the cheapest audit you can run this week, and &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;I am happy to look at it with you&lt;/a&gt;.&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>architecture</category><category>microservices</category><category>laravel</category><category>scaling</category><category>devops</category></item><item><title>Stateless vs stateful apps: the architecture split</title><link>https://ansezz.com/blog/stateless-vs-stateful-apps/</link><guid isPermaLink="true">https://ansezz.com/blog/stateless-vs-stateful-apps/</guid><description>Stateful servers remember; stateless servers forget by design. Why horizontal scaling, sticky sessions, and shared Redis decide the architecture split.</description><pubDate>Tue, 23 Jun 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Scaling a web application often feels like trying to upgrade a jet engine while the plane is mid-flight.&lt;/p&gt;

- Stateful servers remember users in local memory, which forces sticky sessions and breaks when you add nodes.
- Stateless servers forget every request, so any node can serve anyone. That is what makes horizontal scaling easy.
- Shared storage like Redis lets an app feel stateful to users while each server stays stateless.

&lt;p&gt;You start with a single server that handles every request perfectly. But as your traffic grows, you add more servers, and suddenly everything breaks.&lt;/p&gt;
&lt;p&gt;Users are getting logged out randomly. Shopping carts are disappearing into thin air. The database is screaming under the pressure of redundant session checks.&lt;/p&gt;
&lt;p&gt;This chaos usually stems from a fundamental architectural decision made in the early stages of development. You are likely struggling with the friction between stateless and stateful design patterns.&lt;/p&gt;
&lt;p&gt;If your application relies on the server remembering who a user is based on local memory, you are building a stateful system. This works great for small projects but becomes a nightmare when you need to scale horizontally.&lt;/p&gt;
&lt;p&gt;On the other hand, moving to a fully stateless model requires a complete rethink of how you handle authentication and data persistence.&lt;/p&gt;
&lt;p&gt;You need to understand the trade-offs between stateless and stateful apps before you can build reliable, fast software in the cloud.&lt;/p&gt;
&lt;h2&gt;Defining state in the digital world&lt;/h2&gt;
&lt;p&gt;Before comparing the two architectures, we must define what &quot;state&quot; actually means in a web context.&lt;/p&gt;
&lt;p&gt;State is any data that the application needs to remember between different interactions. This could be a user&apos;s login status, the items in a Shopify cart, or the progress of a multi-step form.&lt;/p&gt;
&lt;p&gt;In a traditional web application, the server manages this state by creating a unique session for every visitor. The server stores a small file or a piece of memory linked to a specific session ID.&lt;/p&gt;
&lt;p&gt;When the user moves from one page to another, the server looks up that ID and retrieves the state. This makes the application &quot;stateful&quot; because the server&apos;s response to a request depends on what happened in previous requests.&lt;/p&gt;
&lt;h2&gt;The stateless architecture: the forgetful master&lt;/h2&gt;
&lt;p&gt;A stateless application treats every single HTTP request as a completely new event. The server does not remember anything about the client once the request is finished.&lt;/p&gt;
&lt;p&gt;A user clicks a button, the server processes the data, sends a response, and immediately forgets that user ever existed.&lt;/p&gt;
&lt;figure&gt;
&lt;p&gt;For this to work, the client must provide all the necessary information with every single request. This is why stateless apps often use JSON Web Tokens (JWT) or API keys.&lt;/p&gt;
&lt;p&gt;The token contains the user&apos;s identity and permissions. When the server receives the token, it validates it, performs the requested action, and sends back the result.&lt;/p&gt;
&lt;h3&gt;Why stateless scales&lt;/h3&gt;
&lt;p&gt;The primary advantage of this approach is horizontal scalability. Since the server does not store any local session data, any server in your cluster can handle any request.&lt;/p&gt;
&lt;p&gt;You can add ten more servers to your stack using a tool like &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;Coolify or Docker&lt;/a&gt; and the load balancer can distribute traffic without worrying about where the user&apos;s session is located.&lt;/p&gt;
&lt;p&gt;This same property is what lets a stateless tier sit cleanly behind an &lt;a href=&quot;https://ansezz.com/blog/api-gateway-ai-stack/&quot;&gt;API gateway&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;The stateful architecture: the memory expert&lt;/h2&gt;
&lt;p&gt;Stateful applications are built on the premise of continuity. The server maintains a persistent connection or a session record for every active user.&lt;/p&gt;
&lt;p&gt;This was the default way of building the web for decades. If you are using Laravel with standard Blade templates and the built-in authentication guard, you are likely running a stateful application.&lt;/p&gt;
&lt;p&gt;In a stateful system, the server&apos;s internal memory or local disk stores the user&apos;s context. This makes development faster and easier for certain features.&lt;/p&gt;
&lt;p&gt;For example, &quot;flashing&quot; a success message to the next page is trivial in a stateful app. The server just puts the message in the session and reads it on the next load.&lt;/p&gt;
&lt;h3&gt;The sticky session problem&lt;/h3&gt;
&lt;p&gt;However, statefulness introduces a &quot;sticky session&quot; problem. If you have three servers (A, B, and C) and a user&apos;s session is stored on Server A, the load balancer must ensure that every subsequent request from that user goes back to Server A.&lt;/p&gt;
&lt;p&gt;If the user hits Server B, that server will have no record of them, and they will appear logged out.&lt;/p&gt;
&lt;p&gt;Sticky sessions make scaling significantly more complex and create a single point of failure.&lt;/p&gt;
&lt;p&gt;If Server A crashes, all users &quot;stuck&quot; to it lose their session data.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Stateless vs stateful apps: key differences at a glance&lt;/h2&gt;
&lt;p&gt;Choosing between these two paths depends on your specific technical requirements. Below is a breakdown of how they compare across critical engineering metrics.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Stateless Apps&lt;/th&gt;
&lt;th&gt;Stateful Apps&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Data storage&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;State is stored on the client or a shared database/cache.&lt;/td&gt;
&lt;td&gt;State is stored in the server&apos;s memory or local storage.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Scalability&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;High. Any server can process any request.&lt;/td&gt;
&lt;td&gt;Low. Requires sticky sessions or complex synchronization.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Resilience&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;High. If a server dies, another one takes over instantly.&lt;/td&gt;
&lt;td&gt;Moderate. Server failure often leads to session loss.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Higher initial setup for token management and external caching.&lt;/td&gt;
&lt;td&gt;Lower initial setup for small-scale projects.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Performance&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Potential overhead from passing tokens or fetching data from Redis.&lt;/td&gt;
&lt;td&gt;Faster local memory access but slower overall scaling.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;Practical implementation in Laravel&lt;/h2&gt;
&lt;p&gt;In the world of PHP development, Laravel gives you the flexibility to choose either path. By default, the &lt;code&gt;web&lt;/code&gt; middleware group uses stateful sessions.&lt;/p&gt;
&lt;p&gt;It stores a session cookie on the browser and matches it to a server-side entry, which since Laravel 11 lands in the &lt;code&gt;database&lt;/code&gt; driver out of the box. This is perfect for traditional dashboards where you need simple state management and cookie-based CSRF protection.&lt;/p&gt;
&lt;p&gt;To make your Laravel app stateless, you move toward token-based authentication using Laravel Sanctum or Passport.&lt;/p&gt;
&lt;p&gt;You skip session cookies on your API routes and let every request carry its own bearer token, validating the user against a shared store like Redis or the database. This shift is essential when building backends for mobile apps or complex React/Vue frontends.&lt;/p&gt;
&lt;p&gt;This is also where the stateless model pays off as you grow. Because no node owns a session, you can lean on &lt;a href=&quot;https://ansezz.com/blog/horizontal-vs-vertical-scaling/&quot;&gt;horizontal scaling&lt;/a&gt; and add capacity behind the load balancer without any session-affinity gymnastics.&lt;/p&gt;

Open your production `.env` and check `SESSION_DRIVER`. If it says `file` and you run more than one node, that is your random-logout bug.

&lt;h2&gt;Scaling with Shopify and modern e-commerce&lt;/h2&gt;
&lt;p&gt;Shopify provides an interesting look at how these architectures live together. The Shopify platform itself is a massive distributed system.&lt;/p&gt;
&lt;p&gt;While the &quot;state&quot; of a store (orders, inventory, customers) is preserved in giant databases, the web tier that handles incoming traffic is designed to be stateless. This allows Shopify to handle massive spikes during Black Friday by spinning up thousands of web workers that don&apos;t need to share local memory.&lt;/p&gt;
&lt;p&gt;If you are building &lt;a href=&quot;https://ansezz.com/blog/agentic-commerce-shopify/&quot;&gt;agentic commerce solutions on Shopify&lt;/a&gt;, your app architecture should lean toward statelessness. Your app will receive webhooks and API calls from various Shopify nodes.&lt;/p&gt;
&lt;p&gt;If your app is stateful and relies on local memory to track a multi-step checkout process, you will likely encounter race conditions or lost data as Shopify&apos;s infrastructure scales.&lt;/p&gt;
&lt;p&gt;Using a shared Redis instance to store temporary job state is the professional way to handle this.&lt;/p&gt;
&lt;h2&gt;DevOps and deployment considerations&lt;/h2&gt;
&lt;p&gt;Your choice between stateless vs stateful apps will dictate your DevOps strategy. Stateless apps are the &quot;gold standard&quot; for containerization.&lt;/p&gt;
&lt;p&gt;Since they have no local dependencies, you can run them in Docker containers and deploy them to any cloud provider without friction. You don&apos;t need to worry about preserving the &quot;health&quot; of a specific server instance.&lt;/p&gt;
&lt;h3&gt;Stateful apps need more care&lt;/h3&gt;
&lt;p&gt;Stateful apps require much more care. If you are deploying a stateful Laravel app, you must ensure that your session driver is set to something central like Redis or a database.&lt;/p&gt;
&lt;p&gt;Laravel 11 and later default to the &lt;code&gt;database&lt;/code&gt; driver, but if you switch it back to &lt;code&gt;file&lt;/code&gt;, each node writes sessions to its own disk and your horizontal scaling will fail.&lt;/p&gt;
&lt;p&gt;You also need to consider how you handle deployments. A &quot;zero-downtime&quot; deployment is harder when you have thousands of active sessions living in server memory. You often have to wait for sessions to drain before taking a node offline.&lt;/p&gt;

Before your next deploy, take one node out of the load balancer and watch whether any users get logged out. That tells you how stateful you really are.


- **Stateless apps** treat every request as a new event, requiring the client to provide context (tokens) every time.
- **Stateful apps** remember user interactions through local server memory or session files, making them easier to build but harder to scale.
- **Horizontal scaling** is the primary driver for choosing a stateless architecture. It allows you to add servers without session conflicts.
- **Laravel** supports both. Use sessions for simple web apps and tokens (Sanctum) for scalable APIs.
- **Shared storage** (like Redis) is the bridge that allows an application to feel stateful to the user while remaining stateless at the server level.
- **Shopify developers** should prioritize stateless designs to handle the platform&apos;s distributed nature and high-volume webhooks.

&lt;p&gt;How are you managing session persistence in your current production environment to ensure horizontal scaling?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>architecture</category><category>scaling</category><category>laravel</category><category>redis</category><category>devops</category><category>shopify</category></item><item><title>Synchronous vs asynchronous communication</title><link>https://ansezz.com/blog/synchronous-vs-asynchronous-communication/</link><guid isPermaLink="true">https://ansezz.com/blog/synchronous-vs-asynchronous-communication/</guid><description>The technical differences between synchronous and asynchronous architectures in Laravel and Shopify, and how queues, jobs, and webhooks help you scale.</description><pubDate>Tue, 16 Jun 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A slow API call inside a web request ties up a worker that every other user is waiting for.&lt;/p&gt;

- Synchronous calls block: the worker waits until the task finishes. Fine for fast reads and writes, dangerous for slow third-party APIs.
- Asynchronous work goes on a queue and runs in a background worker, so the user gets an instant response and failed jobs can retry.
- In Laravel and Shopify that means: dispatch jobs for slow work, and answer webhooks fast, then process them in a job.

&lt;p&gt;Every developer has faced the dreaded &quot;spinning wheel of death.&quot; You click a button, the browser hangs, and you wait five seconds for a confirmation that never feels fast enough.&lt;/p&gt;
&lt;p&gt;This lag usually comes from a synchronous process holding the entire request-response cycle hostage while it waits for a third-party API or a heavy database query.&lt;/p&gt;
&lt;p&gt;In high-traffic environments, these blocking calls are more than a nuisance. They are a scalability killer that can bring down your entire infrastructure.&lt;/p&gt;
&lt;p&gt;Architecting for scale means knowing when to keep things synchronous and when to move them to the background. This decision affects everything from user experience to server costs.&lt;/p&gt;
&lt;p&gt;By shifting heavy lifting to asynchronous workers, you decouple your system. This lets your application handle thousands of concurrent users without breaking a sweat.&lt;/p&gt;
&lt;h2&gt;The blocking nature of synchronous communication&lt;/h2&gt;
&lt;p&gt;Synchronous communication is the traditional request-response model. When a client sends a request, it waits for the server to process the logic and return a response.&lt;/p&gt;
&lt;p&gt;This is a &quot;blocking&quot; operation. The execution thread is tied up until the task completes.&lt;/p&gt;
&lt;h3&gt;Like a phone call&lt;/h3&gt;
&lt;p&gt;Think of it like a phone call. You dial a number, wait for the other person to pick up, and you cannot do anything else until the conversation is over.&lt;/p&gt;
&lt;p&gt;In web development, this is perfectly fine for simple operations like fetching a user profile or updating a single database row. The latency is minimal and the user needs the data immediately to continue.&lt;/p&gt;
&lt;h3&gt;When sync becomes dangerous&lt;/h3&gt;
&lt;p&gt;Synchronous flows become dangerous when you add external dependencies. If your Laravel controller calls the Shopify Admin API to update 500 products during a standard HTTP request, your PHP worker is stuck.&lt;/p&gt;
&lt;p&gt;If Shopify takes three seconds to respond, that worker cannot serve any other users for those three seconds.&lt;/p&gt;
&lt;p&gt;Under heavy load, your worker pool will run out. This leads to 504 Gateway Timeout errors and a broken experience.&lt;/p&gt;

Find your three slowest controller actions in your APM or logs. For each one, note whether the time is spent waiting on an external API. Those are your first candidates for a queue.

&lt;h2&gt;The fire-and-forget power of asynchronous logic&lt;/h2&gt;
&lt;p&gt;Asynchronous communication decouples the request from the processing. The client sends a message or triggers an event and immediately receives a response.&lt;/p&gt;
&lt;p&gt;The actual work happens &quot;out of band&quot; in a separate process or at a later time.&lt;/p&gt;
&lt;h3&gt;Like sending an email&lt;/h3&gt;
&lt;p&gt;This is more like sending an email. You hit send and go straight back to your day. The recipient reads and processes the message whenever they are available.&lt;/p&gt;
&lt;p&gt;In a technical stack, this is done with message queues like Redis or Amazon SQS, or a dedicated broker such as &lt;a href=&quot;https://ansezz.com/blog/scaling-with-rabbitmq/&quot;&gt;RabbitMQ&lt;/a&gt;.&lt;/p&gt;

  &lt;div&gt;A phone call. The worker waits on the line until the task is done, and nobody else can use it.&lt;/div&gt;
  &lt;div&gt;An email. The job goes on a queue, the user gets an answer right away, and a background worker does the rest.&lt;/div&gt;

&lt;figure&gt;
&lt;h3&gt;What belongs in the background&lt;/h3&gt;
&lt;p&gt;When you move a task to an asynchronous worker, the user gets an instant &quot;Success&quot; message. The heavy processing happens in the background. This architecture is essential for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Sending transactional emails.&lt;/li&gt;
&lt;li&gt;Generating PDF reports or data exports.&lt;/li&gt;
&lt;li&gt;Communicating with third-party APIs like Shopify or Stripe.&lt;/li&gt;
&lt;li&gt;Running complex AI agents or RAG pipelines.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Laravel queues and background jobs&lt;/h2&gt;
&lt;p&gt;Laravel gives you asynchronous processing through its Queue system. Instead of performing a slow task in your controller, you dispatch a &quot;Job.&quot;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Synchronous (Bad for slow tasks)
public function store(Request $request) {
    $order = Order::create($request-&amp;gt;all());
    Mail::to($request-&amp;gt;user())-&amp;gt;send(new OrderConfirmed($order)); // Waits for SMTP
    return response()-&amp;gt;json($order);
}

// Asynchronous (Scalable)
public function store(Request $request) {
    $order = Order::create($request-&amp;gt;all());
    ProcessOrderEmail::dispatch($order); // Returns immediately
    return response()-&amp;gt;json($order);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Workers and retries&lt;/h3&gt;
&lt;p&gt;By using &lt;code&gt;dispatch()&lt;/code&gt;, you push a payload into Redis. A separate process, managed by a tool like &lt;a href=&quot;https://laravel.com/docs/horizon&quot;&gt;Laravel Horizon&lt;/a&gt;, picks up the job and runs it. This keeps your web-facing workers free to handle more incoming traffic.&lt;/p&gt;
&lt;p&gt;If the email server is down and the job has retries configured (&lt;code&gt;$tries&lt;/code&gt; and &lt;code&gt;$backoff&lt;/code&gt; on the job, or &lt;code&gt;--tries&lt;/code&gt; on the worker), the job goes back on the queue and tries again later.&lt;/p&gt;
&lt;p&gt;This kind of resilience is impossible in a strictly synchronous world.&lt;/p&gt;

Open one of your job classes and set `public $tries = 5;` and `public $backoff = [10, 60, 300];`. Laravel&apos;s default is a single attempt, so without this a failed job just fails.

&lt;h2&gt;Shopify webhooks: the event-driven standard&lt;/h2&gt;
&lt;p&gt;For e-commerce developers, understanding asynchronous communication is mandatory when working with Shopify. Shopify uses webhooks to notify your application of events like &lt;code&gt;orders/create&lt;/code&gt; or &lt;code&gt;products/update&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;Five seconds to answer&lt;/h3&gt;
&lt;p&gt;Webhooks are asynchronous by design. Shopify does not wait for your app to process the entire order. It sends the POST request and expects a &lt;code&gt;2xx&lt;/code&gt; response within five seconds.&lt;/p&gt;
&lt;p&gt;If your code tries to run complex inventory logic or sync data to an ERP synchronously within that webhook route, you risk timing out.&lt;/p&gt;
&lt;h3&gt;Retries and removal&lt;/h3&gt;
&lt;p&gt;Shopify then retries the failed delivery up to eight times over roughly four hours, which can mean duplicate processing if your handler is not idempotent.&lt;/p&gt;
&lt;p&gt;Worse, if your endpoint keeps failing, Shopify removes the webhook subscription entirely, and you stop receiving events until you re-register it.&lt;/p&gt;
&lt;p&gt;Receive the webhook, validate the signature, dispatch a Laravel Job, and return the response immediately.&lt;/p&gt;
&lt;p&gt;This is the best practice for &lt;a href=&quot;https://ansezz.com/blog/agentic-commerce-shopify/&quot;&gt;agentic commerce on Shopify&lt;/a&gt;. It keeps your app responsive and keeps Shopify happy with your delivery rates.&lt;/p&gt;
&lt;figure&gt;

Time your webhook route end to end. If anything after the HMAC check takes more than a few hundred milliseconds, move it into a job and return `200` first.

&lt;h2&gt;Infrastructure impact and DevOps considerations&lt;/h2&gt;
&lt;p&gt;Moving to an asynchronous architecture changes how you manage your infrastructure. In a synchronous world, you scale your web servers to handle peak traffic. In an asynchronous world, you scale your workers.&lt;/p&gt;
&lt;h3&gt;Separate web and worker containers&lt;/h3&gt;
&lt;p&gt;Tools like &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;Coolify and Docker&lt;/a&gt; make it easier to manage these separate services. You can run your web container on one set of resources and your worker containers on another.&lt;/p&gt;
&lt;p&gt;If you get a massive spike in background jobs, you can spin up more workers without affecting the performance of your main website.&lt;/p&gt;
&lt;h3&gt;Managed queues&lt;/h3&gt;
&lt;p&gt;For cross-service communication, Google Cloud Tasks is a strong alternative to a self-hosted queue. It dispatches HTTP callbacks to any endpoint with built-in rate limiting, scheduling, and retries.&lt;/p&gt;
&lt;p&gt;This is particularly useful when building an &lt;a href=&quot;https://ansezz.com/blog/api-gateway-ai-stack/&quot;&gt;API gateway for AI stacks&lt;/a&gt;, where different microservices need to talk to each other without blocking the main user flow.&lt;/p&gt;
&lt;h2&gt;When to choose sync vs async&lt;/h2&gt;
&lt;p&gt;Choosing the right pattern depends on the user&apos;s expectations and the reliability of the task.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Synchronous&lt;/th&gt;
&lt;th&gt;Asynchronous&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;User Experience&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Immediate feedback required.&lt;/td&gt;
&lt;td&gt;Background processing is okay.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Data Integrity&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Result needed for next step.&lt;/td&gt;
&lt;td&gt;Eventual consistency is okay.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Reliability&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Fails if the connection breaks.&lt;/td&gt;
&lt;td&gt;Can retry on failure (set $tries).&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Simple code structure.&lt;/td&gt;
&lt;td&gt;Requires queue management and workers.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Example Use Case&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Login validation, viewing a cart.&lt;/td&gt;
&lt;td&gt;Order fulfillment, image processing.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3&gt;Use synchronous when:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;The operation is extremely fast (under 100ms).&lt;/li&gt;
&lt;li&gt;The user cannot proceed without the result of the operation.&lt;/li&gt;
&lt;li&gt;You are performing a simple read/write to your primary database.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Use asynchronous when:&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;You are calling an external API.&lt;/li&gt;
&lt;li&gt;The task takes more than 200ms to complete.&lt;/li&gt;
&lt;li&gt;The task can fail and needs to be retried.&lt;/li&gt;
&lt;li&gt;You are performing bulk operations on large datasets.&lt;/li&gt;
&lt;/ul&gt;

Designing for high performance means not making every user wait on every task. By embracing asynchronous communication, you build systems that are more reliable and easier to scale.
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Identify bottlenecks&lt;/strong&gt;: Use tools like Laravel Telescope or OpenTelemetry to find slow controller actions.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Offload everything&lt;/strong&gt;: If it doesn&apos;t need to happen &lt;em&gt;right now&lt;/em&gt;, push it to a queue.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Handle webhooks fast&lt;/strong&gt;: Always return a 200 response to Shopify immediately and process the logic later.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Monitor your workers&lt;/strong&gt;: Use dashboards like Laravel Horizon to track queue health and failure rates.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Design for retries&lt;/strong&gt;: Ensure your background jobs are idempotent, meaning they can run multiple times without causing side effects.
&lt;/li&gt;&lt;/ol&gt;

&lt;p&gt;How are you currently handling long-running API tasks in your Laravel or Shopify application?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>laravel</category><category>shopify</category><category>devops</category><category>architecture</category><category>messaging</category></item><item><title>REST vs gRPC: two API philosophies</title><link>https://ansezz.com/blog/rest-vs-grpc/</link><guid isPermaLink="true">https://ansezz.com/blog/rest-vs-grpc/</guid><description>The technical differences between REST and gRPC: when to use Protocol Buffers over JSON for high-performance microservices, and why good designs use both.</description><pubDate>Sun, 14 Jun 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;REST is built for humans and browsers. gRPC is built for machines talking to machines. Good architectures use each where it fits.&lt;/p&gt;

- gRPC sends compact binary Protocol Buffers over HTTP/2, with a contract-first `.proto` schema, generated stubs and native streaming.
- REST sends human-readable JSON over plain HTTP that every browser and tool understands, which makes it the default for public APIs.
- The common pattern: REST at the public edge, gRPC between internal services.

&lt;p&gt;Choosing between REST and gRPC is a choice of architectural philosophy as much as protocol, and it shapes how your services communicate.&lt;/p&gt;
&lt;p&gt;Pick the wrong one for a high-traffic microservice environment and you will spend your time fighting network latency and rising cloud costs as JSON payloads bloat under load.&lt;/p&gt;
&lt;p&gt;Force a binary protocol onto a public-facing web client and you break the interoperability that makes the modern web work.&lt;/p&gt;
&lt;p&gt;The choice between Representational State Transfer (REST) and gRPC (a Google-built RPC framework whose name is a recursive joke: &quot;gRPC Remote Procedure Calls&quot;) is a trade-off between human readability and machine efficiency.&lt;/p&gt;
&lt;p&gt;REST has been the champion of the web for decades, while gRPC has quickly become the preferred choice for internal service-to-service communication. Understanding both is essential for any engineer building scalable systems in 2026.&lt;/p&gt;
&lt;h2&gt;The mechanical advantage of gRPC&lt;/h2&gt;
&lt;p&gt;At its core, gRPC is built to be fast. It gets there by moving away from the text-based nature of REST and using a binary format called Protocol Buffers (Protobuf).&lt;/p&gt;
&lt;h3&gt;The JSON overhead&lt;/h3&gt;
&lt;p&gt;In a typical REST interaction, your server takes an object, serializes it into a JSON string, and sends it over the wire. The receiving server then parses that string back into an object.&lt;/p&gt;
&lt;p&gt;This process is CPU-intensive and creates large payloads, because JSON includes every key name in every single message.&lt;/p&gt;
&lt;h3&gt;How Protobuf avoids it&lt;/h3&gt;
&lt;p&gt;Protobuf is a strongly typed binary serialization format. Because the schema is defined in advance in a &lt;code&gt;.proto&lt;/code&gt; file, the messages do not need to include field names. Instead, they use small numeric tags to identify each field.&lt;/p&gt;
&lt;p&gt;The payload savings depend heavily on data shape. Numeric and structured data shrinks a lot, often to several times smaller than the equivalent JSON, while large free-text fields see less benefit.&lt;/p&gt;
&lt;p&gt;Either way, binary Protobuf parsing is typically much faster than JSON parsing, which cuts serialization CPU in high-throughput environments.&lt;/p&gt;
&lt;h3&gt;HTTP/2 underneath&lt;/h3&gt;
&lt;p&gt;Another pillar of gRPC is HTTP/2. Many REST implementations still run on HTTP/1.1, but gRPC requires HTTP/2, which brings request multiplexing.&lt;/p&gt;
&lt;p&gt;In HTTP/1.1, a client effectively sends one request at a time over a connection, which leads to application-level head-of-line blocking. HTTP/2 multiplexes many requests and responses over a single TCP connection and removes that HTTP-layer blocking.&lt;/p&gt;
&lt;p&gt;(TCP-level head-of-line blocking still exists under packet loss. That is the problem HTTP/3 and QUIC were designed to solve.) This efficiency matters for modern &lt;a href=&quot;https://ansezz.com/blog/api-gateway-ai-stack/&quot;&gt;API gateway architectures&lt;/a&gt; that handle thousands of concurrent requests.&lt;/p&gt;
&lt;figure&gt;

Take one real response from your busiest internal endpoint, write the matching `.proto` message, and compare the encoded size with the JSON size. That ratio, for your data, is the number that matters.

&lt;h2&gt;The universality of REST&lt;/h2&gt;
&lt;p&gt;If gRPC is so much faster, why hasn&apos;t it replaced REST? The answer lies in the browser.&lt;/p&gt;
&lt;p&gt;Browsers cannot speak native gRPC directly. gRPC-Web exists, but it needs a proxy in front of your services and does not support every streaming mode.&lt;/p&gt;
&lt;h3&gt;Resources and verbs&lt;/h3&gt;
&lt;p&gt;REST was born from the architecture of the web itself. It treats every piece of data as a resource that can be accessed with standard HTTP verbs like GET, POST, PUT, and DELETE. This resource-oriented approach makes it intuitive and easy to consume.&lt;/p&gt;
&lt;p&gt;Every web browser, every language, and every command-line tool like &lt;code&gt;curl&lt;/code&gt; understands REST. If you are building a public API that third-party developers will use, REST is usually the right choice.&lt;/p&gt;
&lt;h3&gt;Inspectability&lt;/h3&gt;
&lt;p&gt;The barrier to entry is almost zero. A developer can open their browser console and immediately see what your API returns in a human-readable format. This &quot;inspectability&quot; is a big advantage for debugging and onboarding.&lt;/p&gt;
&lt;h3&gt;Flexibility&lt;/h3&gt;
&lt;p&gt;REST is also flexible. It does not require a strict contract to function. Tools like OpenAPI (Swagger) provide structure, but a REST API can still evolve loosely.&lt;/p&gt;
&lt;p&gt;This flexibility suits startups and small teams that need to iterate quickly. When you are deploying a new SaaS product on &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;Coolify or Docker&lt;/a&gt;, the simplicity of a RESTful interface often outweighs the performance gains of gRPC in the early stages.&lt;/p&gt;
&lt;h2&gt;Schema-first vs resource-first development&lt;/h2&gt;
&lt;p&gt;One of the biggest differences between these two philosophies is how you actually write code. gRPC forces a &quot;contract-first&quot; approach.&lt;/p&gt;
&lt;p&gt;You must define your service and your message types in a &lt;code&gt;.proto&lt;/code&gt; file before you write a single line of application logic.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// A typical gRPC service definition
service ProductService {
  rpc GetProduct (ProductRequest) returns (ProductResponse);
}

message ProductRequest {
  string id = 1;
}

message ProductResponse {
  string name = 1;
  double price = 2;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Generated stubs, shared types&lt;/h3&gt;
&lt;p&gt;Once this file is defined, gRPC tools generate client and server stubs in the language of your choice. This gives you strong typing across services.&lt;/p&gt;
&lt;p&gt;If you have a Go backend talking to a Python microservice, the Protobuf contract ensures both sides agree on the data structure. This removes a whole class of bugs caused by missing fields or incorrect types in JSON.&lt;/p&gt;
&lt;h3&gt;The risk of API drift&lt;/h3&gt;
&lt;p&gt;REST typically follows a &quot;resource-first&quot; or &quot;implementation-first&quot; approach. You define your routes and your controllers, and then you might generate documentation later.&lt;/p&gt;
&lt;p&gt;This allows faster prototyping, but it can lead to &quot;API drift,&quot; where the documentation and the actual implementation fall out of sync. In a large &lt;a href=&quot;https://ansezz.com/blog/monolith-vs-microservices/&quot;&gt;microservice ecosystem&lt;/a&gt;, this lack of strict contracts can become a maintenance nightmare.&lt;/p&gt;

  &lt;div&gt;Write routes and controllers, document later. Fast to prototype, easy to drift out of sync.&lt;/div&gt;
  &lt;div&gt;Write the `.proto` contract first, generate typed stubs for every language. Slower to start, hard to drift.&lt;/div&gt;


If you keep REST, generate an OpenAPI spec from your code in CI and fail the build when it changes without a matching docs update. You get some of gRPC&apos;s contract safety without switching protocols.

&lt;h2&gt;Streaming and real-time capabilities&lt;/h2&gt;
&lt;p&gt;Another area where gRPC shines is native streaming. Because it is built on HTTP/2, gRPC supports four types of communication:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Unary:&lt;/strong&gt; A single request and a single response (the typical REST pattern).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Server streaming:&lt;/strong&gt; The client sends one request and the server sends back a stream of messages.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Client streaming:&lt;/strong&gt; The client sends a stream of messages and the server responds once.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Bidirectional streaming:&lt;/strong&gt; Both client and server send a stream of messages simultaneously.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Streaming as a first-class feature&lt;/h3&gt;
&lt;p&gt;This makes gRPC a strong candidate for real-time applications like chat services, stock tickers, or IoT telemetry feeds.&lt;/p&gt;
&lt;p&gt;In the world of REST, you would typically reach for WebSockets or Server-Sent Events (SSE) to get similar results. These are often treated as &quot;add-ons&quot; to the API rather than a core part of the protocol. With gRPC, streaming is built in.&lt;/p&gt;
&lt;h3&gt;A streaming example&lt;/h3&gt;
&lt;p&gt;Imagine a system that processes a large dataset of vector embeddings for an AI application. A client could stream the data to the server, and the server could stream back the results as they are processed.&lt;/p&gt;
&lt;p&gt;This reduces the memory footprint on both ends, because the entire dataset never needs to be loaded into RAM at once.&lt;/p&gt;
&lt;h2&gt;Choosing between REST and gRPC for 2026&lt;/h2&gt;
&lt;p&gt;Base the decision on your &quot;consumer.&quot;&lt;/p&gt;
&lt;h3&gt;Humans and browsers: REST&lt;/h3&gt;
&lt;p&gt;If your consumer is a human developer or a web browser, choose REST. The ecosystem of tools, from Postman to Chrome DevTools, is simply too mature to ignore. REST is the language of the public web.&lt;/p&gt;
&lt;h3&gt;Servers and constrained devices: gRPC&lt;/h3&gt;
&lt;p&gt;If your consumer is another server, or a performance-constrained device like a mobile phone or an IoT sensor, gRPC is usually the better choice. The gains in serialization and the reduced network overhead save you money on bandwidth and compute.&lt;/p&gt;
&lt;h3&gt;Both, in one architecture&lt;/h3&gt;
&lt;p&gt;In a modern architecture, it is common to see both living together. A RESTful API gateway handles incoming traffic from the internet, then talks to internal microservices using gRPC.&lt;/p&gt;
&lt;p&gt;If you are building for the web, start with REST. If you are building for the cloud at scale, master gRPC.&lt;/p&gt;
&lt;p&gt;As we move further into &lt;a href=&quot;https://ansezz.com/blog/ai-vs-traditional-development/&quot;&gt;AI-integrated development&lt;/a&gt;, the efficiency of these data pipelines matters even more. Large language models and agentic systems need low-latency access to data, which makes gRPC a natural fit for the &quot;inner loop&quot; of AI infrastructure.&lt;/p&gt;
&lt;figure&gt;

Draw your current service map and mark each arrow &quot;browser or third party&quot; or &quot;service to service.&quot; The first kind stays REST. The busiest arrow of the second kind is your first gRPC candidate.


- **Performance:** gRPC is usually faster than REST thanks to binary serialization (Protobuf) and HTTP/2 multiplexing.
- **Payload size:** Protobuf messages are smaller than JSON because they omit redundant field names and use compact binary encoding, though the gain depends on data shape.
- **Contract-first:** gRPC requires a strict schema definition, leading to better type safety and less &quot;API drift&quot; in large systems.
- **Interoperability:** REST remains the king of the public web and browser-based clients due to its human-readable JSON format and native browser support.
- **Streaming:** gRPC supports native bidirectional streaming, making it ideal for real-time data pipelines and IoT.
- **Hybrid approach:** Many modern architectures use REST for the public-facing edge and gRPC for internal service-to-service communication.

&lt;p&gt;If you&apos;re designing services like this for production, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams ship it&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Are you prepared to handle the added complexity of a contract-first architecture in exchange for smaller payloads and faster serialization?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>api-design</category><category>microservices</category><category>devops</category></item><item><title>Serverless vs containers: the 2026 engineering guide</title><link>https://ansezz.com/blog/serverless-vs-containers/</link><guid isPermaLink="true">https://ansezz.com/blog/serverless-vs-containers/</guid><description>Compare Serverless vs Containers for performance, cost, and scalability. Learn why hybrid models are winning for Laravel and Shopify applications in 2026.</description><pubDate>Sun, 14 Jun 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Serverless wins when traffic is spiky and tasks are short. Containers win when traffic is steady and processes run long. Most 2026 stacks use both.&lt;/p&gt;

- Serverless (FaaS) hides the whole runtime: it scales per request and to zero, but you pay with cold starts, time limits and a stateless design.
- Containers package the full runtime: portable, no execution limit and steady latency, at the cost of owning images, scanning and memory.
- Serverless containers like Google Cloud Run blend the two, so your main app runs as a container while bursty side tasks use functions.

&lt;p&gt;Developers are drowning in YAML files and server patches while the business demands faster shipping. Managing infrastructure often feels like a full-time job that has nothing to do with writing actual code.&lt;/p&gt;
&lt;p&gt;When your application hits a sudden traffic spike during a flash sale or a viral product launch, the &quot;504 Gateway Timeout&quot; becomes your worst enemy. If your infrastructure cannot scale in seconds, you lose revenue and customer trust.&lt;/p&gt;
&lt;p&gt;The choice between Serverless vs Containers is a strategic decision as much as a technical one. It sets your operational overhead and your ability to stay lean.&lt;/p&gt;
&lt;p&gt;In 2026, the lines between these technologies have blurred. We see serverless containers and event-driven architectures that mix both worlds. This guide breaks down the engineering substance of Serverless vs Containers to help you decide where to host your next Laravel application or Shopify integration.&lt;/p&gt;
&lt;h2&gt;Understanding the architectural split&lt;/h2&gt;
&lt;p&gt;The debate over Serverless vs Containers is often simplified into &quot;no servers&quot; vs &quot;virtual servers.&quot; In reality, the difference lies in the abstraction layer.&lt;/p&gt;
&lt;h3&gt;Serverless&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Serverless&lt;/strong&gt; (often called Function-as-a-Service or FaaS) abstracts the entire execution environment. You upload code, and the provider (AWS Lambda, Google Cloud Functions) handles the trigger, the scaling, and the underlying OS.&lt;/p&gt;
&lt;p&gt;It is event-driven by design. Your code stays dormant until an HTTP request, a file upload, or a database change wakes it up.&lt;/p&gt;
&lt;h3&gt;Containers&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Containers&lt;/strong&gt; (Docker, Kubernetes) package the entire runtime environment: the application code, libraries, and system dependencies. You have full control over the operating system version and the configuration.&lt;/p&gt;
&lt;p&gt;Containers run on infrastructure you manage (or semi-manage via Fargate or Cloud Run). They are typically &quot;always on&quot; or need specific scaling rules to spin up and down.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Serverless (FaaS)&lt;/th&gt;
&lt;th&gt;Containers (Docker/K8s)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Control&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Minimal; provider-managed&lt;/td&gt;
&lt;td&gt;High; you define the image&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Scaling&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Automatic per request&lt;/td&gt;
&lt;td&gt;Orchestrator-managed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;State&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Strictly stateless&lt;/td&gt;
&lt;td&gt;Can be stateful&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Runtime&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Limited to provider support&lt;/td&gt;
&lt;td&gt;Anything that can be Dockerized&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Timeout&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Usually 15 minutes or less&lt;/td&gt;
&lt;td&gt;No inherent execution limit&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;Serverless: the high-speed execution engine&lt;/h2&gt;
&lt;p&gt;Serverless is the tool for developers who want to ignore infrastructure. The main advantage is the &quot;scale-to-zero&quot; model. When no one is using your app, you pay nothing.&lt;/p&gt;
&lt;p&gt;When traffic surges, the provider spins up new instances of your function automatically, within account concurrency limits. AWS Lambda defaults to 1,000 concurrent executions per region (raisable on request) and scales out at roughly 1,000 new environments every 10 seconds.&lt;/p&gt;
&lt;h3&gt;The cold start penalty&lt;/h3&gt;
&lt;p&gt;The catch is the &quot;cold start.&quot; When a function hasn&apos;t been used recently, the provider must provision a container and boot your runtime.&lt;/p&gt;
&lt;p&gt;Lightweight runtimes like Node.js and Go start fast natively, and provisioned concurrency keeps instances warm. Heavier runtimes feel it more.&lt;/p&gt;
&lt;p&gt;That is why AWS built SnapStart (first for Java, later .NET and Python) to snapshot an initialized runtime and cut cold starts sharply. For frameworks like PHP, cold starts remain a factor that needs careful planning.&lt;/p&gt;
&lt;h3&gt;Perfect for glue code&lt;/h3&gt;
&lt;p&gt;Serverless is perfect for &quot;glue code.&quot; If you are building a &lt;a href=&quot;https://ansezz.com/blog/agentic-commerce-shopify/&quot;&gt;Shopify app architecture&lt;/a&gt; that needs to process webhooks or resize images on the fly, serverless functions are very efficient.&lt;/p&gt;
&lt;p&gt;They absorb the bursty, unpredictable nature of webhooks without a dedicated server sitting idle 99% of the time.&lt;/p&gt;
&lt;figure&gt;

Open your Lambda logs and count the `REPORT` lines that include `Init Duration`. Their share of all invocations is your real cold start rate, and it tells you whether provisioned concurrency or SnapStart is worth paying for.

&lt;h2&gt;Containers: the universal blueprint&lt;/h2&gt;
&lt;p&gt;Containers offer a level of portability that serverless cannot match. A Docker image that runs on your local machine runs the same way on AWS ECS, Google Cloud Run, or a self-hosted &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;Coolify instance&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Long-running work&lt;/h3&gt;
&lt;p&gt;For long-running processes or heavy compute tasks, containers are the standard. If your application needs a persistent WebSocket server, heavy machine learning inference, or long-running cron jobs that exceed 15 minutes, containers are the natural fit.&lt;/p&gt;
&lt;p&gt;(Managed add-ons like API Gateway WebSockets can bridge some of this for functions, but the long-lived process itself belongs in a container.)&lt;/p&gt;
&lt;h3&gt;The operational tax&lt;/h3&gt;
&lt;p&gt;The main drawback is the &quot;operational tax.&quot; Even with managed services like AWS Fargate, you are still responsible for your Dockerfiles, image security scanning, and making sure your containers don&apos;t run out of memory.&lt;/p&gt;
&lt;p&gt;You are managing the environment, even if you aren&apos;t managing the physical hardware.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# A typical Laravel Dockerfile for a containerized approach
FROM php:8.4-fpm-alpine

# Install system dependencies
RUN apk add --no-cache libpng-dev libzip-dev zip unzip git

# Install PHP extensions
RUN docker-php-ext-install pdo_mysql gd zip

# Set working directory
WORKDIR /var/www

# Copy application code
COPY . .

# Install composer dependencies
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
RUN composer install --no-dev --optimize-autoloader

CMD [&quot;php-fpm&quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Technical head-to-head: latency and cost&lt;/h2&gt;
&lt;p&gt;When comparing Serverless vs Containers, cost is the most common point of confusion. Serverless looks cheaper because you only pay for what you use. This is true for low-traffic or spiky applications.&lt;/p&gt;
&lt;h3&gt;The cost crossover&lt;/h3&gt;
&lt;p&gt;At a certain level of sustained traffic, containers become more cost-effective. Once your application handles thousands of requests per minute consistently, the per-invocation cost of serverless starts to exceed the monthly cost of a reserved container instance.&lt;/p&gt;

  &lt;div&gt;Serverless usually costs less: you pay per request and nothing while idle.&lt;/div&gt;
  &lt;div&gt;Containers usually cost less: a reserved instance beats paying per invocation thousands of times a minute.&lt;/div&gt;

&lt;h3&gt;Latency and jitter&lt;/h3&gt;
&lt;p&gt;Latency is the other big trade-off. Containers offer &quot;warm&quot; execution. Since the process is already running, the time-to-first-byte (TTFB) is consistent.&lt;/p&gt;
&lt;p&gt;Serverless performance can be &quot;jittery.&quot; One request might take 30ms while the next (a cold start) takes several hundred milliseconds.&lt;/p&gt;
&lt;p&gt;For an interactive admin dashboard, this inconsistency can frustrate users. It also ties directly into how you architect &lt;a href=&quot;https://ansezz.com/blog/stateless-vs-stateful-apps/&quot;&gt;stateless vs stateful apps&lt;/a&gt;, since serverless forces a strictly stateless design.&lt;/p&gt;

Take last month&apos;s request count and average duration, and price them on your provider&apos;s function calculator. Then price one always-on container that can handle your peak. The cheaper line tells you which side of the crossover you are on.

&lt;h2&gt;Laravel and Shopify: where to host?&lt;/h2&gt;
&lt;p&gt;For a modern Laravel application, the choice often comes down to &lt;strong&gt;Laravel Vapor&lt;/strong&gt; (Serverless) vs &lt;strong&gt;Docker on Cloud Run/Coolify&lt;/strong&gt; (Containers).&lt;/p&gt;
&lt;h3&gt;The case for serverless Laravel&lt;/h3&gt;
&lt;p&gt;If you are building a SaaS with unpredictable growth, Laravel Vapor is a strong option. It handles the complexity of deploying a full-stack PHP framework to AWS Lambda.&lt;/p&gt;
&lt;p&gt;It manages your assets on S3 and handles database scaling. It is the &quot;easy button&quot; for high-scale Laravel apps that don&apos;t want a dedicated DevOps engineer.&lt;/p&gt;
&lt;h3&gt;The case for containerized Laravel&lt;/h3&gt;
&lt;p&gt;If your application is &quot;always on&quot; and involves heavy background processing (like syncing thousands of products for a Shopify store), containers are the better fit.&lt;/p&gt;
&lt;p&gt;Docker lets you run your HTTP layer, your queue workers, and your scheduler in one consistent environment. This setup matches your local development environment, which cuts down the &quot;it works on my machine&quot; bugs.&lt;/p&gt;
&lt;h2&gt;The 2026 hybrid reality&lt;/h2&gt;
&lt;p&gt;Modern engineering has moved past the binary choice of Serverless vs Containers. We are now in the era of &lt;strong&gt;serverless containers&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;Services like Google Cloud Run let you package your app as a container and still get the autoscaling and pay-per-use benefits of serverless.&lt;/p&gt;
&lt;h3&gt;A note on AWS&lt;/h3&gt;
&lt;p&gt;AWS App Runner played that role on AWS, but it stopped accepting new customers on April 30, 2026. AWS now points new container apps to ECS Express Mode, which runs on Fargate and does not scale to zero.&lt;/p&gt;
&lt;h3&gt;Mix and match&lt;/h3&gt;
&lt;p&gt;You can deploy your main Laravel API as a container on Cloud Run, which scales to zero when idle. At the same time, you can use pure serverless functions (like AWS Lambda) for specific, isolated tasks like PDF generation or sending transactional emails.&lt;/p&gt;
&lt;p&gt;Your core business logic stays in a predictable container, while your bursty, auxiliary tasks scale independently.&lt;/p&gt;
&lt;p&gt;This hybrid approach puts each workload in the environment that suits it.&lt;/p&gt;
&lt;figure&gt;

List your app&apos;s background tasks and mark each one &quot;short and bursty&quot; or &quot;long or steady.&quot; Move one short, bursty task (PDF generation, image resizing) to a function and leave the rest in your container.


Choosing between Serverless vs Containers needs an honest look at your team&apos;s skills and your application&apos;s traffic patterns.
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Choose Serverless&lt;/strong&gt; if your traffic is spiky, you have a small team with no DevOps experience, and your tasks are short-lived (under 15 minutes). It is the fastest path from code to production for event-driven systems.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Choose Containers&lt;/strong&gt; if you have steady, high-volume traffic, require specific OS libraries, or need long-running background processes. It offers the best price-to-performance ratio for &quot;always-on&quot; applications.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Go Hybrid&lt;/strong&gt; if you want the best of both worlds. Use a serverless container platform like Cloud Run for your web app and FaaS for your side effects.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Laravel developers:&lt;/strong&gt; Vapor is great for AWS-centric teams, but Dockerized deployments on platforms like Coolify offer more control and lower long-term costs for many regional businesses.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Shopify developers:&lt;/strong&gt; Use serverless functions for webhooks to prevent bottlenecks during peak sales events like Black Friday, but keep your admin UI in a container for consistent speed.
&lt;/li&gt;&lt;/ul&gt;

&lt;p&gt;If you&apos;re weighing serverless against containers, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams make that call&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If you had to migrate your core API today, would you prioritize the absolute control of a Dockerfile or the operational freedom of an event-driven function?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>infrastructure</category><category>docker</category><category>laravel</category><category>shopify</category></item><item><title>Monolith vs microservices: how to choose</title><link>https://ansezz.com/blog/monolith-vs-microservices/</link><guid isPermaLink="true">https://ansezz.com/blog/monolith-vs-microservices/</guid><description>Monolith vs microservices: the real technical trade-offs for Laravel and Shopify teams, when each pays off, and why a modular monolith often wins.</description><pubDate>Wed, 10 Jun 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Microservices are not the default goal. For most Laravel and Shopify teams, a well-structured monolith ships faster and costs less.&lt;/p&gt;

- A monolith is one deployable unit: simple deploys, shared memory, ACID data and easy end-to-end tests.
- Microservices buy independent scaling, team autonomy and fault isolation, but charge a &quot;network tax&quot; of latency, partial failures and eventual consistency.
- A modular monolith with strict internal boundaries is often the best middle ground, and it makes a later split much easier.

&lt;p&gt;Complexity is the silent killer of engineering velocity. You start with a clean codebase and a clear vision.&lt;/p&gt;
&lt;p&gt;Within months, your deployment times have doubled and your team is tripping over each other&apos;s pull requests. You face the classic crossroads: monolith vs microservices.&lt;/p&gt;
&lt;h3&gt;The cost of choosing wrong&lt;/h3&gt;
&lt;p&gt;Choosing the wrong path early can lead to catastrophic technical debt, or operational overhead that drains your budget before you find product-market fit.&lt;/p&gt;
&lt;h3&gt;Resist the default&lt;/h3&gt;
&lt;p&gt;In modern web development, especially with Laravel or Shopify, the pressure to adopt microservices is huge. The industry often treats distributed systems as the default goal.&lt;/p&gt;
&lt;p&gt;For many businesses, a well-structured monolith is both the starting point and the most efficient way to scale. Here is the engineering behind both patterns, to help you decide for your next project on Google Cloud or AWS.&lt;/p&gt;
&lt;h2&gt;Defining the monolithic architecture&lt;/h2&gt;
&lt;p&gt;A monolithic architecture is a unified software model where all components are interconnected and interdependent.&lt;/p&gt;
&lt;p&gt;In Laravel, your routes, controllers, models and background jobs live in one repository. It is a single deployable unit: when you push code, the whole application is built and shipped to your server or container.&lt;/p&gt;
&lt;h3&gt;Why simple wins&lt;/h3&gt;
&lt;p&gt;Monoliths are often unfairly called &quot;legacy.&quot; In reality, they offer big advantages for rapid development.&lt;/p&gt;
&lt;p&gt;All modules share the same memory space and database, so communication between parts of the system is nearly instant. No network latency, API versioning or complex distributed transactions. For a Shopify app or a custom web solution, that simplicity means faster shipping.&lt;/p&gt;
&lt;h3&gt;The benefits of a single codebase&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Simplified deployment:&lt;/strong&gt; you need only one CI/CD pipeline. Whether you use GitHub Actions to deploy to a &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;Docker-based host&lt;/a&gt; or a VPS, the process stays straightforward.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cross-cutting concerns:&lt;/strong&gt; authentication, logging and caching are easier when they are central. You don&apos;t replicate them across multiple services.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;End-to-end testing:&lt;/strong&gt; testing the whole user journey is simpler because you can run the full stack on one machine without complex orchestration.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;The microservices shift&lt;/h2&gt;
&lt;p&gt;Microservices break the application into small, independent services that talk over a network. Each focuses on one business domain, such as billing, user management or inventory.&lt;/p&gt;
&lt;p&gt;They are often containerized with Docker and managed by orchestrators like Kubernetes or Google Kubernetes Engine (GKE).&lt;/p&gt;
&lt;h3&gt;Team autonomy&lt;/h3&gt;
&lt;p&gt;The main drivers are scalability and team autonomy. When your team grows beyond 15 or 20 developers, a monolith can become a bottleneck.&lt;/p&gt;
&lt;p&gt;Microservices let different squads own parts of the system. One team updates the billing service in Go while another updates the Shopify sync engine in PHP, and a bug in one service is less likely to take down the whole application.&lt;/p&gt;
&lt;h3&gt;When to consider microservices&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Independent scaling needs:&lt;/strong&gt; if your Shopify webhook processing needs heavy CPU but your admin dashboard is lightly used, microservices let you scale only the heavy parts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Technology diversity:&lt;/strong&gt; you might need a Python service for AI-driven &lt;a href=&quot;https://ansezz.com/blog/7-rag-mistakes-production/&quot;&gt;RAG systems&lt;/a&gt; while keeping your core business logic in Laravel.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Fault isolation:&lt;/strong&gt; a crash in the reporting service should not stop customers from checking out.&lt;/li&gt;
&lt;/ul&gt;
&lt;figure&gt;
&lt;h2&gt;Monolith vs microservices: comparing the trade-offs&lt;/h2&gt;
&lt;p&gt;The choice is always a trade-off between simplicity and flexibility. There is no silver bullet: you weigh operational cost against developer experience.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Monolith&lt;/th&gt;
&lt;th&gt;Microservices&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Operational complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Low&lt;/td&gt;
&lt;td&gt;High&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Development speed&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Fast (early stage)&lt;/td&gt;
&lt;td&gt;Slow (early stage)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Scalability&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Vertical / horizontal (whole)&lt;/td&gt;
&lt;td&gt;Independent per service&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Data consistency&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Strong (ACID)&lt;/td&gt;
&lt;td&gt;Eventual consistency&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Network latency&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Minimal&lt;/td&gt;
&lt;td&gt;Significant (API hops)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Testing&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Simple&lt;/td&gt;
&lt;td&gt;Complex distributed testing&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3&gt;The hidden cost of distribution&lt;/h3&gt;
&lt;p&gt;Microservices add a &quot;network tax.&quot; Every call from one service to another adds latency, and you must handle partial failures.&lt;/p&gt;
&lt;p&gt;If the user service is down, how does the order service react? Patterns like &lt;a href=&quot;https://ansezz.com/blog/circuit-breakers-vector-db/&quot;&gt;circuit breakers&lt;/a&gt; and retries become mandatory. That is code with nothing to do with your business logic: pure infrastructure overhead.&lt;/p&gt;
&lt;p&gt;Every service boundary you add is a network call that can fail and a contract you have to keep.&lt;/p&gt;

Count how many teams deploy your app independently today. If the answer is one, write down the specific pain a split would fix before you plan any services.

&lt;h2&gt;Laravel and Shopify context&lt;/h2&gt;
&lt;p&gt;For most &lt;a href=&quot;https://ansezz.com/blog/category/shopify/&quot;&gt;Shopify development&lt;/a&gt; or &lt;a href=&quot;https://ansezz.com/blog/category/laravel/&quot;&gt;Laravel projects&lt;/a&gt;, the &quot;Majestic Monolith&quot; is the better choice.&lt;/p&gt;
&lt;p&gt;Shopify gives you a solid platform-as-a-service (PaaS) foundation. Your backend&apos;s main job is often to handle OAuth, process webhooks and manage a custom database.&lt;/p&gt;
&lt;h3&gt;The distributed monolith&lt;/h3&gt;
&lt;p&gt;Splitting a Shopify app into microservices too early often leads to &quot;distributed monolith&quot; syndrome: the complexity of microservices with components that are still tightly coupled.&lt;/p&gt;
&lt;p&gt;If you cannot deploy Service A without also deploying Service B, you have missed the benefits of the architecture. You have only added network latency and deployment pain.&lt;/p&gt;
&lt;h2&gt;Cloud strategy on GCP&lt;/h2&gt;
&lt;p&gt;Google Cloud Platform (GCP) has good tools for both patterns.&lt;/p&gt;
&lt;h3&gt;Monolith on Cloud Run&lt;/h3&gt;
&lt;p&gt;For a monolith, Cloud Run is a strong choice. It hides server management and scales your container based on request traffic. It is cost-effective because you only pay when your code is running.&lt;/p&gt;
&lt;h3&gt;Microservices with Pub/Sub&lt;/h3&gt;
&lt;p&gt;For microservices, you might use GKE or a set of Cloud Run services connected through &lt;a href=&quot;https://ansezz.com/blog/event-driven-pubsub/&quot;&gt;Pub/Sub&lt;/a&gt;. That gives you asynchronous communication.&lt;/p&gt;
&lt;p&gt;When a Shopify order is created, the &quot;Order Service&quot; publishes an event to Pub/Sub. The &quot;Shipping Service&quot; and &quot;Email Service&quot; both listen for it and act independently.&lt;/p&gt;
&lt;p&gt;This architecture is capable, but it needs real investment in observability tools like Cloud Logging and Cloud Trace to debug issues across service boundaries.&lt;/p&gt;
&lt;h2&gt;The hybrid approach: modular monolith&lt;/h2&gt;
&lt;p&gt;You don&apos;t have to choose between a &quot;big ball of mud&quot; and a complex mesh of services. The modular monolith is an effective middle ground.&lt;/p&gt;
&lt;p&gt;You keep a single codebase and database, but you strictly enforce boundaries inside the code.&lt;/p&gt;
&lt;h3&gt;Boundaries in Laravel&lt;/h3&gt;
&lt;p&gt;In Laravel, this means separate namespaces or even local packages for different domains. Your &quot;Billing&quot; code should not call the &quot;Inventory&quot; models directly. It should use internal interfaces or events.&lt;/p&gt;
&lt;p&gt;You get the deployment simplicity of a monolith while making it easy to extract a module into a standalone microservice later.&lt;/p&gt;

  &lt;div&gt;Billing queries Inventory tables directly, and any change can break any other part of the app.&lt;/div&gt;
  &lt;div&gt;Billing talks to Inventory through an interface or an event. One deploy, but each module can be pulled out later without a rewrite.&lt;/div&gt;

&lt;figure&gt;
&lt;h3&gt;Defer the decision&lt;/h3&gt;
&lt;p&gt;I go deeper on the mechanics (contracts, schema-per-module and the friction signals that justify a split) in &lt;a href=&quot;https://ansezz.com/blog/modular-monolith-first/&quot;&gt;modular monoliths first&lt;/a&gt;. &quot;Deferred decision making&quot; is often the wisest move in software engineering.&lt;/p&gt;
&lt;p&gt;When the time comes to carve a module out, my guide on going &lt;a href=&quot;https://ansezz.com/blog/monolith-to-microservices/&quot;&gt;from monolith to microservices&lt;/a&gt; walks through the strangler-fig migration step by step.&lt;/p&gt;

Pick two domains in your Laravel app (for example Billing and Inventory) and search for direct model calls between them. Replace one with an interface or event this week.


- **Start with a monolith.** Unless you are building for a large organization with multiple teams, microservice overhead will slow you down.
- **Enforce boundaries early.** A modular structure inside your monolith prevents spaghetti code and keeps future scaling possible.
- **Use managed services.** GCP Cloud Run for hosting and Cloud SQL for your database keep the DevOps burden low.
- **Scale components before splitting apps.** Use queues (Laravel Horizon) and background workers for heavy tasks before moving to full microservices.
- **Monitor and trace.** Whatever the architecture, invest in central logging and performance monitoring to find bottlenecks before users feel them.

&lt;p&gt;If you&apos;re weighing a split, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help Laravel and Shopify teams choose between a modular monolith and services&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Are you finding that your current monolithic deployment is hitting performance ceilings that vertical scaling can no longer solve?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>devops</category><category>laravel</category><category>shopify</category><category>infrastructure</category><category>cloud-platforms</category></item><item><title>Load balancer vs reverse proxy: scale vs security</title><link>https://ansezz.com/blog/load-balancer-vs-reverse-proxy/</link><guid isPermaLink="true">https://ansezz.com/blog/load-balancer-vs-reverse-proxy/</guid><description>Reverse proxies handle SSL, caching, and security; load balancers handle scale and availability. The differences, and how to layer both in a Laravel stack.</description><pubDate>Mon, 08 Jun 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A reverse proxy decides how a request is handled. A load balancer decides where it goes. Most production stacks need both.&lt;/p&gt;

- A reverse proxy shields your app: it terminates SSL, caches responses, routes by path and hides your backend servers.
- A load balancer spreads traffic across a pool of identical servers with round robin, least connections or IP hash, and drops unhealthy nodes.
- In production you layer them: a load balancer at the edge, Nginx on each node, and your Laravel app behind it.

&lt;p&gt;Your server is gasping for air. A traffic spike from a marketing campaign or a product launch on Shopify has pushed your single Laravel instance to its limit.&lt;/p&gt;
&lt;p&gt;CPU is pinned at 99 percent, requests are timing out and the database is struggling with the number of open connections. You know you need to scale and put a buffer between the internet and your app.&lt;/p&gt;
&lt;h3&gt;Two terms, two jobs&lt;/h3&gt;
&lt;p&gt;When you look at architecture diagrams, you see two terms used almost interchangeably: load balancer and reverse proxy.&lt;/p&gt;
&lt;p&gt;Choosing the wrong one, or missing how they work together, leads to &quot;Frankenstein&quot; architectures. You might add layers that add latency without adding value, or leave your app exposed to risks a proper proxy would have blocked.&lt;/p&gt;
&lt;p&gt;To build a solid &lt;a href=&quot;https://ansezz.com/blog/category/laravel/&quot;&gt;Laravel&lt;/a&gt; application or a fast &lt;a href=&quot;https://ansezz.com/blog/category/shopify/&quot;&gt;Shopify&lt;/a&gt; app, you need to know how these two components differ.&lt;/p&gt;
&lt;h2&gt;The gatekeeper: understanding the reverse proxy&lt;/h2&gt;
&lt;p&gt;A reverse proxy is a server that sits in front of one or more web servers and intercepts client requests. It acts as a shield and a middleman.&lt;/p&gt;
&lt;p&gt;Users talk to the reverse proxy first. It decides how to handle the request before passing it to your backend Laravel or Node.js application.&lt;/p&gt;
&lt;p&gt;If you are fuzzy on which direction it faces, see &lt;a href=&quot;https://ansezz.com/blog/forward-proxy-vs-reverse-proxy/&quot;&gt;forward proxy vs reverse proxy&lt;/a&gt;. They sit on opposite ends of the connection.&lt;/p&gt;
&lt;h3&gt;Nginx does the dirty work&lt;/h3&gt;
&lt;p&gt;In the world of &lt;a href=&quot;https://ansezz.com/blog/coolify-self-hosted-saas/&quot;&gt;Coolify and self-hosted SaaS&lt;/a&gt;, Nginx is the most common reverse proxy.&lt;/p&gt;
&lt;p&gt;Instead of exposing your application server directly to the internet, the reverse proxy handles the &quot;dirty work&quot; of HTTP communication.&lt;/p&gt;
&lt;h3&gt;Key functions of a reverse proxy&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;SSL termination:&lt;/strong&gt; encrypting and decrypting HTTPS traffic is CPU-intensive. The proxy handles the certificates and takes this work off your app server, so your Laravel workers focus on business logic instead of handshakes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Caching:&lt;/strong&gt; a reverse proxy can store copies of static assets or even dynamic responses. When a second user requests the same data, the proxy serves it from cache instead of hitting your app. (Nginx, for example, keeps cached responses on disk with the keys held in shared memory.) This cuts backend load a lot.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Request routing:&lt;/strong&gt; you can route by URL path. For example, send every request starting with &lt;code&gt;/api&lt;/code&gt; to one service and everything else to a frontend app.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Security and anonymity:&lt;/strong&gt; hiding your backend IP addresses makes it much harder for attackers to target your servers directly. A proxy can also act as a basic Web Application Firewall (WAF) to block malicious traffic patterns.&lt;/li&gt;
&lt;/ul&gt;
&lt;figure&gt;

Check whether your app server is reachable directly by its public IP. If it is, put Nginx (or your platform&apos;s proxy) in front and close the app port to the outside.

&lt;h2&gt;The traffic controller: understanding the load balancer&lt;/h2&gt;
&lt;p&gt;A load balancer&apos;s mission is high availability and &lt;a href=&quot;https://ansezz.com/blog/horizontal-vs-vertical-scaling/&quot;&gt;horizontal scaling&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If you have five identical Laravel servers running in a &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;Docker&lt;/a&gt; cluster, the load balancer makes sure no single server gets overwhelmed while others sit idle.&lt;/p&gt;
&lt;h3&gt;Layer 4 vs layer 7&lt;/h3&gt;
&lt;p&gt;Layer 4 load balancers work at the transport level (TCP/UDP). They decide based on IP addresses and ports without looking at the request content.&lt;/p&gt;
&lt;p&gt;Layer 7 load balancers work at the application level (HTTP/HTTPS). They can route on headers, cookies or URL parameters.&lt;/p&gt;
&lt;h3&gt;How load balancers distribute work&lt;/h3&gt;
&lt;p&gt;Load balancers use algorithms to decide which server gets the next request:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Round robin:&lt;/strong&gt; requests go to servers in a loop. It is simple but assumes all your backend servers have the same capacity.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Least connections:&lt;/strong&gt; the load balancer tracks active requests per server and sends new traffic to the least busy one.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;IP hash:&lt;/strong&gt; the client&apos;s IP picks the server, so a user stays on the same server. That matters for apps that store session data locally instead of in Redis.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The proxy cares about each request. The balancer cares about the whole pool.&lt;/p&gt;
&lt;h2&gt;Technical nuances: comparing the two&lt;/h2&gt;
&lt;p&gt;The confusion often comes from tools like Nginx, HAProxy and Traefik that can do both jobs. The difference in concept still matters for system design.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Reverse Proxy&lt;/th&gt;
&lt;th&gt;Load Balancer&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Primary Goal&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Security, routing, and efficiency&lt;/td&gt;
&lt;td&gt;Availability and throughput&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Backend Pattern&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Usually one logical service&lt;/td&gt;
&lt;td&gt;A pool of identical nodes&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Caching&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Excellent support for static + dynamic&lt;/td&gt;
&lt;td&gt;Usually minimal or none&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Health Checks&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Basic (is the backend up?)&lt;/td&gt;
&lt;td&gt;Advanced (latency, error rates, load)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;OSI Layer&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Mostly Layer 7 (Application)&lt;/td&gt;
&lt;td&gt;Layer 4 (Transport) or Layer 7&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3&gt;Same family, different focus&lt;/h3&gt;
&lt;p&gt;Both are reverse-proxy roles wearing different hats. A load balancer focuses on &lt;em&gt;distribution&lt;/em&gt; (spreading traffic across a pool). A reverse proxy focuses on &lt;em&gt;transformation&lt;/em&gt; (SSL, caching, routing, security).&lt;/p&gt;
&lt;p&gt;The same tool (Nginx, HAProxy, Traefik) can do both. In a full &lt;a href=&quot;https://ansezz.com/blog/api-gateway-ai-stack/&quot;&gt;API gateway&lt;/a&gt;, these roles merge into a single entry point that manages both security and distribution across your microservices.&lt;/p&gt;
&lt;h2&gt;Real-world implementation in Laravel and Shopify&lt;/h2&gt;
&lt;p&gt;When building custom web solutions, you rarely pick only one. You layer them. A production Laravel app usually looks like a &quot;sandwich&quot; of these components.&lt;/p&gt;
&lt;h3&gt;The Laravel DevOps stack&lt;/h3&gt;
&lt;p&gt;In a typical cloud setup on GCP or AWS, the request flow looks like this:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The cloud load balancer:&lt;/strong&gt; your public entry point. It receives traffic and spreads it across virtual machines or Kubernetes nodes.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The local reverse proxy (Nginx):&lt;/strong&gt; each node runs Nginx. It terminates SSL, serves static CSS and JS from disk and forwards PHP requests to PHP-FPM.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The application (Laravel):&lt;/strong&gt; Laravel receives the cleaned-up request from Nginx.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This gives you redundancy. If one Nginx instance fails, the cloud load balancer sees it through a health check and stops sending traffic to that node, so users stay served.&lt;/p&gt;

  &lt;div&gt;Laravel handles SSL, static files and every request on one box. When it fails or fills up, the whole site goes down.&lt;/div&gt;
  &lt;div&gt;A cloud load balancer health-checks several nodes. Nginx on each node handles SSL and static files, and Laravel only runs business logic.&lt;/div&gt;

&lt;h3&gt;The Shopify app context&lt;/h3&gt;
&lt;p&gt;Shopify apps have their own needs. During big events like Black Friday, webhook traffic can spike hard and in bursts.&lt;/p&gt;
&lt;p&gt;Shopify gives you only five seconds to respond to each delivery before it counts as failed. It retries failed deliveries 8 times over the next 4 hours, and after 8 consecutive failures a subscription created through the Admin API is deleted. You cannot ride that out on a single server.&lt;/p&gt;
&lt;h3&gt;Acknowledge fast, process later&lt;/h3&gt;
&lt;p&gt;Use a load balancer to take in these webhooks and spread them across a fleet of worker nodes. Acknowledge fast and process the payload &lt;a href=&quot;https://ansezz.com/blog/synchronous-vs-asynchronous-communication/&quot;&gt;asynchronously&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;A reverse proxy at the edge can add rate limiting. That stops a single store from hogging your app&apos;s resources and keeps your &lt;a href=&quot;https://ansezz.com/blog/agentic-commerce-shopify/&quot;&gt;agentic commerce systems&lt;/a&gt; responsive for all merchants.&lt;/p&gt;
&lt;figure&gt;

Time your Shopify webhook handler end to end. If it does real work before returning 200, move that work to a queue job and return right away.

&lt;h2&gt;Why &quot;both&quot; is usually the answer&lt;/h2&gt;
&lt;p&gt;Modern web development has moved away from the &quot;one server&quot; model. Even for small startups, a managed load balancer costs little compared to downtime.&lt;/p&gt;
&lt;p&gt;A reverse proxy like Nginx or Traefik is standard practice because it keeps your application code simple. You don&apos;t want SSL handling logic inside your Laravel controllers.&lt;/p&gt;
&lt;h3&gt;Blue-green deployments&lt;/h3&gt;
&lt;p&gt;Combining a load balancer and a reverse proxy lets you run blue-green deployments. You spin up a new version, test it, then switch the load balancer from the old version to the new one.&lt;/p&gt;
&lt;p&gt;If something breaks, you flip the switch back. You need both components working together to get this level of control.&lt;/p&gt;

Add a health check endpoint (for example `/up`) to your Laravel app and point your load balancer&apos;s health check at it, so a broken node leaves the rotation on its own.


- **Use a reverse proxy** if you have a single server but need SSL, caching and basic security.
- **Add a load balancer** as soon as you need to scale across multiple servers or need high availability.
- **Use Nginx or HAProxy** to fill both roles in one software layer for small and medium projects.
- **Offload SSL termination** to the proxy layer to keep your Laravel or Node.js app responsive.
- **Set up health checks** in your load balancer to remove unhealthy servers from the rotation automatically.
- **Choose layer 7 balancing** if you need to route on HTTP headers or URL paths.

&lt;p&gt;If you&apos;re putting a proxy and load balancer in front of a Laravel or Shopify app, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams set up SSL, caching and scaling layers for production&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;What is your current bottleneck: scaling the number of concurrent connections, or managing the complexity of your request routing?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>devops</category><category>laravel</category><category>shopify</category><category>infrastructure</category><category>networking</category><category>scaling</category></item><item><title>Load balancer vs API gateway</title><link>https://ansezz.com/blog/load-balancer-vs-api-gateway/</link><guid isPermaLink="true">https://ansezz.com/blog/load-balancer-vs-api-gateway/</guid><description>Load balancers distribute traffic; API gateways enforce policy. The real differences, when to use each, and how to layer both in a production stack.</description><pubDate>Sun, 07 Jun 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Two boxes sit at the front of almost every production system. One spreads traffic so nothing falls over. The other decides who gets in and where they go.&lt;/p&gt;

- A load balancer spreads traffic across identical backends at L4 or L7, and stays fast because it ignores who is calling.
- An API gateway enforces policy at the edge: auth, rate limits, transformations, caching and routing by intent to the right service.
- Mature stacks run both: a load balancer at the edge, a gateway behind it, and internal load balancers in front of each service.

&lt;p&gt;Engineers constantly confuse these two components. They look similar on an architecture diagram, but they solve very different problems.&lt;/p&gt;
&lt;h3&gt;Picking the wrong one costs you&lt;/h3&gt;
&lt;p&gt;Pick the wrong one and you either bolt fragile business logic onto a component built to be dumb and fast, or you pay for an expensive policy engine to do a job simple round-robin could handle.&lt;/p&gt;
&lt;p&gt;The load balancer vs API gateway decision shapes how you scale, secure and observe everything behind it. Here is what each one does, where they differ and why mature systems almost always run both.&lt;/p&gt;
&lt;h2&gt;What a load balancer actually does&lt;/h2&gt;
&lt;p&gt;A load balancer has one job: take incoming traffic and spread it across a pool of identical backends so no single server gets overwhelmed.&lt;/p&gt;
&lt;p&gt;It is the component that lets you run three copies of your app instead of one and survive a traffic spike.&lt;/p&gt;
&lt;h3&gt;L4 vs L7&lt;/h3&gt;
&lt;p&gt;Load balancers work at one of two layers. An &lt;strong&gt;L4 (transport layer)&lt;/strong&gt; balancer routes by IP and port. It does not look inside the request and just forwards TCP/UDP packets, which makes it extremely fast.&lt;/p&gt;
&lt;p&gt;An &lt;strong&gt;L7 (application layer)&lt;/strong&gt; balancer understands HTTP. It can route based on the path or host header and terminate SSL/TLS. Algorithms like round-robin, least-connections and IP-hash decide which backend gets the next request.&lt;/p&gt;
&lt;h3&gt;Simple on purpose&lt;/h3&gt;
&lt;p&gt;A load balancer is largely &lt;strong&gt;stateless and content-agnostic&lt;/strong&gt;. It cares about availability and distribution, not about who you are or whether you are allowed to make this call.&lt;/p&gt;
&lt;p&gt;That ignorance is a feature: it keeps the component simple, fast and reliable. If you have wondered how this differs from a reverse proxy, the two overlap heavily. See &lt;a href=&quot;https://ansezz.com/blog/load-balancer-vs-reverse-proxy/&quot;&gt;load balancer vs reverse proxy&lt;/a&gt; for where they diverge.&lt;/p&gt;
&lt;h2&gt;What an API gateway actually does&lt;/h2&gt;
&lt;p&gt;An API gateway is the opposite kind of component. It is opinionated, aware and full of business rules. It sits in front of your services as a single, managed front door for every API call.&lt;/p&gt;
&lt;h3&gt;Cross-cutting concerns in one place&lt;/h3&gt;
&lt;p&gt;A gateway handles the &lt;strong&gt;cross-cutting concerns&lt;/strong&gt; you don&apos;t want duplicated in every microservice:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Authentication and JWT validation&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://ansezz.com/blog/rate-limiting-ai-wallet/&quot;&gt;Rate limiting and quota enforcement&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Request/response transformation&lt;/li&gt;
&lt;li&gt;Protocol translation (for example, exposing internal &lt;a href=&quot;https://ansezz.com/blog/rest-vs-grpc/&quot;&gt;gRPC services&lt;/a&gt; as REST/JSON)&lt;/li&gt;
&lt;li&gt;Caching and per-client logging&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Instead of each service re-implementing auth, the gateway enforces it once at the edge.&lt;/p&gt;
&lt;h3&gt;Routing by intent&lt;/h3&gt;
&lt;p&gt;A gateway routes by &lt;strong&gt;intent&lt;/strong&gt; as well as availability. It maps &lt;code&gt;/orders&lt;/code&gt; to the orders service and &lt;code&gt;/users&lt;/code&gt; to the users service, applies the right policy to each and stitches a fleet of microservices into one coherent API.&lt;/p&gt;
&lt;p&gt;That makes it a natural fit once you &lt;a href=&quot;https://ansezz.com/blog/monolith-vs-microservices/&quot;&gt;move from a monolith to microservices&lt;/a&gt; and need one stable front door over many services. It is also the base of a clean &lt;a href=&quot;https://ansezz.com/blog/api-gateway-ai-stack/&quot;&gt;API gateway for an AI stack&lt;/a&gt;, where the gateway governs which model endpoints and tools a request can reach.&lt;/p&gt;
&lt;p&gt;The load balancer asks &quot;is a server free?&quot; The gateway asks &quot;should this request get in at all?&quot;&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Key differences at a glance&lt;/h2&gt;
&lt;p&gt;Both sit at the front and both can route HTTP, but their purpose, intelligence and state are very different.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Aspect&lt;/th&gt;
&lt;th&gt;Load Balancer&lt;/th&gt;
&lt;th&gt;API Gateway&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Primary job&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Distribute traffic across servers&lt;/td&gt;
&lt;td&gt;Enforce policy + route by intent&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Layer&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;L4 (TCP/UDP) or L7 (HTTP)&lt;/td&gt;
&lt;td&gt;L7 (HTTP/API aware)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Awareness&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Content-agnostic&lt;/td&gt;
&lt;td&gt;Inspects auth, headers, payload&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Core features&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Health checks, SSL, algorithms&lt;/td&gt;
&lt;td&gt;Auth, rate limiting, caching, transforms&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;State&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Mostly stateless&lt;/td&gt;
&lt;td&gt;Tracks clients, quotas, sessions&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Optimizes for&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Availability + throughput&lt;/td&gt;
&lt;td&gt;Security + control&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The rule of thumb: reach for a &lt;strong&gt;load balancer&lt;/strong&gt; when you need raw distribution and uptime, and an &lt;strong&gt;API gateway&lt;/strong&gt; when you need to apply rules (who can call this, how often and in what shape).&lt;/p&gt;
&lt;h2&gt;The layered architecture: using them together&lt;/h2&gt;
&lt;p&gt;In production, it is common to see both components working together. Each layer does a different job: one spreads the traffic, the other decides what gets through.&lt;/p&gt;
&lt;h3&gt;A typical request flow&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The L4/L7 load balancer:&lt;/strong&gt; sits at the very edge of your network. It handles global traffic distribution, terminates SSL/TLS and passes clean HTTP traffic to the API gateway.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The API gateway:&lt;/strong&gt; receives traffic from the load balancer. It checks the user&apos;s JWT, confirms they haven&apos;t exceeded their rate limit and routes the request to the correct microservice.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The backend services:&lt;/strong&gt; these often have their own internal load balancers. For example, your Laravel API might run three pods, and a simple internal load balancer (often built into Docker or Kubernetes) spreads the gateway&apos;s traffic across them.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Scale each layer on its own&lt;/h3&gt;
&lt;p&gt;This separation of concerns lets you scale your infrastructure independently of your business rules.&lt;/p&gt;
&lt;p&gt;You can rewrite authentication logic in the gateway without touching load balancer configuration, and you can &lt;a href=&quot;https://ansezz.com/blog/horizontal-vs-vertical-scaling/&quot;&gt;add or remove backend replicas&lt;/a&gt; without the gateway noticing.&lt;/p&gt;

  &lt;div&gt;Each microservice validates JWTs and counts requests its own way. A policy change means editing and redeploying every service.&lt;/div&gt;
  &lt;div&gt;The gateway validates JWTs and enforces rate limits once at the edge. Services trust the gateway and focus on their own work.&lt;/div&gt;


List every place your services check auth or rate limits today. If the same logic lives in more than one service, that logic belongs in a gateway.

&lt;h2&gt;Implementing traffic control with Laravel and Docker&lt;/h2&gt;
&lt;p&gt;When developing with Laravel, you often don&apos;t need a dedicated hardware appliance. You can build these patterns with open-source software like Nginx, Traefik or Kong.&lt;/p&gt;
&lt;p&gt;Using &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;Docker containerization&lt;/a&gt; makes this setup very portable.&lt;/p&gt;
&lt;h3&gt;Traefik labels as a gateway&lt;/h3&gt;
&lt;p&gt;If you use Traefik as an API gateway in a Docker Compose file, you can define your routing and middleware directly in the labels. That keeps your configuration close to your code.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;services:
  laravel-api:
    image: your-org/laravel-app:latest
    labels:
      - &quot;traefik.http.routers.api.rule=Host(`api.example.com`)&quot;
      - &quot;traefik.http.middlewares.api-auth.forwardauth.address=http://auth-service&quot;
      - &quot;traefik.http.middlewares.rate-limit.ratelimit.average=100&quot;
      - &quot;traefik.http.routers.api.middlewares=api-auth,rate-limit&quot;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Here, Traefik plays the API gateway role: it checks with an external auth service and enforces rate limits before the request ever reaches the Laravel application.&lt;/p&gt;

Add a `ratelimit` middleware to one Traefik router in staging, hit it with a quick load test and confirm you get HTTP 429 responses once you pass the limit.

&lt;h2&gt;Shopify and the gateway pattern&lt;/h2&gt;
&lt;p&gt;For Shopify developers, the API gateway pattern is very useful for &quot;headless&quot; storefronts. You talk to both the Shopify Storefront API and your own custom backend, and a gateway can unify these separate sources.&lt;/p&gt;
&lt;p&gt;It can cache frequent Shopify queries to reduce API consumption and speed things up for the end user.&lt;/p&gt;
&lt;h3&gt;Logic Shopify doesn&apos;t offer&lt;/h3&gt;
&lt;p&gt;A gateway also lets you add logic Shopify doesn&apos;t support natively: transforming payloads or merging multiple sources into one response, which cuts the number of round trips the browser makes.&lt;/p&gt;
&lt;p&gt;That pattern is a foundation for building &lt;a href=&quot;https://ansezz.com/blog/agentic-workflows-vibe-coding/&quot;&gt;agentic workflows&lt;/a&gt; in modern commerce.&lt;/p&gt;
&lt;figure&gt;

- **Choose a load balancer** for simple traffic distribution, high throughput and maximum availability at the network layer.
- **Choose an API gateway** for complex routing, security enforcement, protocol translation and a unified entry point to microservices.
- **Layer your stack** with an L4/L7 load balancer at the edge and an API gateway behind it for business logic.
- **Use automation** with tools like Docker and Coolify to manage these components without manual server configuration.
- **Focus on observability** by using the gateway&apos;s per-client metrics for debugging and billing.

&lt;p&gt;If you&apos;re untangling the front door of your production stack, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams design load balancer and API gateway layers&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;How do you handle cross-cutting concerns like rate limiting and authentication across your current microservice fleet?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>api-design</category><category>networking</category><category>architecture</category><category>microservices</category><category>devops</category><category>laravel</category></item><item><title>Horizontal vs vertical scaling</title><link>https://ansezz.com/blog/horizontal-vs-vertical-scaling/</link><guid isPermaLink="true">https://ansezz.com/blog/horizontal-vs-vertical-scaling/</guid><description>Learn the key differences between horizontal and vertical scaling. Discover the right architectural strategy for scaling your web application effectively.</description><pubDate>Sat, 06 Jun 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Your database is at 90% CPU and users feel the lag. The real question is whether you buy a bigger server or add more of them.&lt;/p&gt;

- Vertical scaling adds CPU and RAM to one server: no code changes, but a hard ceiling and a single point of failure.
- Horizontal scaling adds servers behind a load balancer: high availability and elasticity, but your app must be stateless.
- Most teams end up hybrid, scaling the app layer out while keeping the database on one strong primary with read replicas.

&lt;p&gt;Your application is slowing down. Users report latency, your database is hitting 90% CPU usage and your background workers are lagging.&lt;/p&gt;
&lt;p&gt;You know you need more power. Choosing the wrong scaling path can lead to wasted budget, needless complexity or a hard ceiling on your growth.&lt;/p&gt;
&lt;h3&gt;Scaling is a trade-off&lt;/h3&gt;
&lt;p&gt;Adding hardware is only half of the job. The other half is understanding the trade-offs between vertical and horizontal strategies.&lt;/p&gt;
&lt;p&gt;If you wait too long to scale out, you risk a single point of failure. If you scale out too early, you drown in the complexity of distributed systems.&lt;/p&gt;
&lt;h2&gt;Vertical scaling: the &quot;bigger box&quot; strategy&lt;/h2&gt;
&lt;p&gt;Vertical scaling, or &quot;scaling up,&quot; means adding more power to your existing server. This usually means more CPU, RAM or storage on a single instance.&lt;/p&gt;
&lt;p&gt;In a cloud like Google Cloud or AWS, this is as simple as changing your machine type from a small instance to a high-memory or high-compute one.&lt;/p&gt;
&lt;h3&gt;The path of least resistance&lt;/h3&gt;
&lt;p&gt;The application still lives on one machine, so you don&apos;t need to change your code. There is no need for load balancers, service discovery or complex networking.&lt;/p&gt;
&lt;p&gt;Your &lt;a href=&quot;https://ansezz.com/blog/category/laravel/&quot;&gt;Laravel&lt;/a&gt; application or monolith works exactly as it did before, just faster.&lt;/p&gt;
&lt;h3&gt;The hard ceiling&lt;/h3&gt;
&lt;p&gt;Every hardware generation has a limit. Eventually the top machine size available is either too expensive or simply not enough.&lt;/p&gt;
&lt;p&gt;Vertical scaling also does not solve redundancy. If that one big server goes down, your entire system goes down with it.&lt;/p&gt;

Before you buy a bigger box, run your numbers through my [server capacity calculator](/tools/capacity-calculator/) to see how many workers your traffic really needs.

&lt;h2&gt;Horizontal scaling: building the &quot;fleet&quot;&lt;/h2&gt;
&lt;p&gt;Horizontal scaling, or &quot;scaling out,&quot; means adding more machines to your infrastructure. Instead of one giant server, you have a fleet of smaller servers working in parallel.&lt;/p&gt;
&lt;p&gt;A load balancer sits in front of this fleet and spreads incoming traffic across the available nodes.&lt;/p&gt;
&lt;h3&gt;Built for failure&lt;/h3&gt;
&lt;p&gt;This is the gold standard for high availability and modern &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;cloud infrastructure&lt;/a&gt;. When one server fails, the load balancer routes traffic to the healthy ones.&lt;/p&gt;
&lt;p&gt;It is also very elastic. With &lt;a href=&quot;https://ansezz.com/blog/smart-auto-scaling-ai/&quot;&gt;auto-scaling&lt;/a&gt;, you add nodes during a traffic spike and remove them when things quiet down, so you only pay for what you use.&lt;/p&gt;
&lt;h3&gt;The catch: state&lt;/h3&gt;
&lt;p&gt;Horizontal scaling requires architectural changes. Your application must be &lt;a href=&quot;https://ansezz.com/blog/stateless-vs-stateful-apps/&quot;&gt;stateless&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If a user uploads a file to Server A, Server B must be able to access it. If you store session data in Server A&apos;s local memory, the user gets logged out when the next request hits Server B. Move state to shared databases or object storage.&lt;/p&gt;
&lt;p&gt;A fleet only helps when any server can answer any request.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Key differences at a glance&lt;/h2&gt;
&lt;p&gt;Your choice depends on your current stage and technical needs. Here is how the two compare on the engineering metrics that matter most.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Vertical scaling (scale up)&lt;/th&gt;
&lt;th&gt;Horizontal scaling (scale out)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Primary action&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Add CPU/RAM to one node&lt;/td&gt;
&lt;td&gt;Add more nodes to the pool&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Complexity&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Low (no code changes)&lt;/td&gt;
&lt;td&gt;High (distributed system)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Fault tolerance&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Low (single point of failure)&lt;/td&gt;
&lt;td&gt;High (redundancy by design)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Scalability limit&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Hard limit (hardware ceiling)&lt;/td&gt;
&lt;td&gt;Virtually unlimited&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Maintenance&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Requires downtime for resizing&lt;/td&gt;
&lt;td&gt;Zero-downtime rolling updates&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Cost&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Expensive at the high end&lt;/td&gt;
&lt;td&gt;More efficient through auto-scaling&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;The challenge of distributed state&lt;/h2&gt;
&lt;p&gt;When you move to a horizontal model, the database becomes the main bottleneck.&lt;/p&gt;
&lt;p&gt;Scaling the application layer is fairly easy because app servers are usually stateless. Scaling a database is harder because data must stay consistent across multiple nodes. Every new app server also opens its own database connections, and my &lt;a href=&quot;https://ansezz.com/tools/postgres-connection-calculator/&quot;&gt;Postgres connection pool calculator&lt;/a&gt; shows when you will hit &lt;code&gt;max_connections&lt;/code&gt;.&lt;/p&gt;
&lt;h3&gt;Start with read replicas&lt;/h3&gt;
&lt;p&gt;For many &lt;a href=&quot;https://ansezz.com/blog/category/shopify/&quot;&gt;Shopify&lt;/a&gt; apps or custom web platforms, the first step into horizontal scaling is adding &lt;a href=&quot;https://ansezz.com/blog/replication-vs-backup-laravel/&quot;&gt;read replicas&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;You keep one &quot;primary&quot; database for writes and multiple &quot;replica&quot; databases for reads. This takes the heavy read load off the main node.&lt;/p&gt;
&lt;h3&gt;Sharding comes last&lt;/h3&gt;
&lt;p&gt;If your data grows beyond what a single primary node can handle, you might look into sharding. That means splitting your data across different database clusters.&lt;/p&gt;
&lt;p&gt;It works, but it adds a lot of complexity to how you query and join data.&lt;/p&gt;

Check what share of your database queries are reads. If it&apos;s most of them, point those reads at a replica before you think about sharding.

&lt;h2&gt;Scaling in practice: Laravel and DevOps&lt;/h2&gt;
&lt;p&gt;In the Laravel ecosystem, scaling often starts with vertical upgrades. I have seen many projects stay on a single strong VPS for years.&lt;/p&gt;
&lt;p&gt;As traffic grows, the move to horizontal scaling usually follows a clear pattern:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Externalize sessions:&lt;/strong&gt; move sessions from the &lt;code&gt;file&lt;/code&gt; driver to &lt;code&gt;redis&lt;/code&gt; or &lt;code&gt;database&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Centralize files:&lt;/strong&gt; move local storage to an S3-compatible object store.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Add a load balancer:&lt;/strong&gt; use Nginx or a cloud-provider load balancer to distribute traffic.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Decouple workers:&lt;/strong&gt; move queue workers to their own instances so they don&apos;t compete with the web server for resources.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Tooling helps&lt;/h3&gt;
&lt;p&gt;Tools like &lt;a href=&quot;https://ansezz.com/blog/coolify-self-hosted-saas/&quot;&gt;Coolify&lt;/a&gt; or Docker Swarm make managing multiple containers easier. They let you define your infrastructure as code, so spinning up new nodes is simple.&lt;/p&gt;

  &lt;div&gt;Sessions in local files, uploads on local disk, queue workers on the web server. A second server would break logins and lose files.&lt;/div&gt;
  &lt;div&gt;Sessions in Redis, files in S3-compatible storage, workers on their own instances, Nginx in front. Adding a node is a config change.&lt;/div&gt;

&lt;figure&gt;

Switch your session driver from `file` to `redis` in a staging environment and log in through two app instances. If you stay logged in, step one is done.

&lt;h2&gt;How to choose your strategy&lt;/h2&gt;
&lt;p&gt;There is no one-size-fits-all answer. Your choice should balance cost, time and reliability.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Choose vertical scaling if:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You are in the early stages of a startup or MVP.&lt;/li&gt;
&lt;li&gt;Your traffic is predictable and stable.&lt;/li&gt;
&lt;li&gt;You have a small team with limited DevOps resources.&lt;/li&gt;
&lt;li&gt;Your application architecture is tightly coupled or legacy.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;&lt;strong&gt;Choose horizontal scaling if:&lt;/strong&gt;&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You need 99.9% or higher availability.&lt;/li&gt;
&lt;li&gt;Your traffic is bursty or growing fast.&lt;/li&gt;
&lt;li&gt;You are building a cloud-native application from scratch.&lt;/li&gt;
&lt;li&gt;You want to avoid the &quot;all-or-nothing&quot; risk of a single server.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Most teams go hybrid&lt;/h3&gt;
&lt;p&gt;In reality, most modern architectures mix both. You might scale your database vertically as far as you can while scaling your application layer horizontally.&lt;/p&gt;
&lt;p&gt;That gives you the reliability of a fleet with the simplicity of a single data source.&lt;/p&gt;

- Vertical scaling makes a single server stronger through CPU and RAM upgrades.
- Horizontal scaling adds more servers to a pool and uses a load balancer to manage traffic.
- Vertical scaling is simpler and needs no code changes, but it has a performance ceiling and no redundancy.
- Horizontal scaling offers high availability and elasticity, but it requires a stateless application.
- For most web apps, scaling out starts by externalizing sessions, files and background jobs.
- Databases are the hardest part to scale horizontally, often needing replicas or sharding.

&lt;p&gt;If you&apos;re planning a scaling path for your stack, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams move from one server to a fleet without breaking sessions or data&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;At what point does the cost of managing a distributed horizontal system outweigh the cost of simply buying a larger server for your specific workload?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>scaling</category><category>devops</category><category>infrastructure</category><category>laravel</category><category>architecture</category></item><item><title>API vs MCP: connecting AI systems</title><link>https://ansezz.com/blog/api-vs-mcp/</link><guid isPermaLink="true">https://ansezz.com/blog/api-vs-mcp/</guid><description>The core differences between traditional APIs and the Model Context Protocol (MCP), and when to use each to build scalable, agentic AI systems.</description><pubDate>Mon, 01 Jun 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;APIs connect software to software. MCP connects AI agents to software. Mix them up and you spend weeks writing glue code that breaks on the next schema change.&lt;/p&gt;

- Traditional APIs are rigid contracts built for developers who read docs. MCP is a standard, self-describing layer built for models that discover tools at runtime.
- MCP turns the M x N integration problem (every AI client times every tool) into M + N.
- MCP does not replace your APIs. It usually wraps them, so your business logic and security stay in your core services.

&lt;p&gt;Your AI agents are trapped in a silo of brittle, custom-coded API integrations that break the moment you update a schema.&lt;/p&gt;
&lt;p&gt;You spend weeks writing boilerplate glue code just to give a Large Language Model (LLM) access to a single database or a CRM.&lt;/p&gt;
&lt;p&gt;This manual mapping of endpoints to prompts is the hidden tax of modern AI engineering. Every new tool needs a fresh round of documentation reading and prompt tuning.&lt;/p&gt;
&lt;h3&gt;Why APIs alone struggle with agents&lt;/h3&gt;
&lt;p&gt;APIs have powered the internet for decades, but they were never designed for the non-deterministic, reasoning-heavy nature of AI agents.&lt;/p&gt;
&lt;p&gt;We are moving from hard-coded connections to dynamic capability discovery. This is where the Model Context Protocol (MCP) comes in.&lt;/p&gt;
&lt;h2&gt;The API era: the power grid of the web&lt;/h2&gt;
&lt;p&gt;Traditional APIs (Application Programming Interfaces) are the foundation of modern software. Whether it is a RESTful endpoint, a GraphQL query or a gRPC stream, the core idea is the same.&lt;/p&gt;
&lt;p&gt;It is a defined contract for software-to-software communication. You know exactly what input to send, and you get a predictable output back.&lt;/p&gt;
&lt;h3&gt;Rigid by design&lt;/h3&gt;
&lt;p&gt;In AI development, APIs are like the power grid. They provide the raw energy and data your application needs.&lt;/p&gt;
&lt;p&gt;If you are building a &lt;a href=&quot;https://ansezz.com/blog/agentic-commerce-shopify/&quot;&gt;Shopify application&lt;/a&gt;, you use the Shopify Admin API to fetch orders or update inventory. The logic is rigid, the schemas are fixed, and the developer must know exactly which endpoint to call and when.&lt;/p&gt;
&lt;h3&gt;The translation tax&lt;/h3&gt;
&lt;p&gt;The problem starts when you want an LLM to use these tools. You have to write &quot;tool definitions&quot; or &quot;function schemas&quot; that describe the API to the model.&lt;/p&gt;
&lt;p&gt;You are translating the API documentation into a format the model can understand. This works for one or two tools. It does not scale to an entire ecosystem of internal data sources and external services.&lt;/p&gt;
&lt;h2&gt;What is Model Context Protocol?&lt;/h2&gt;
&lt;p&gt;The Model Context Protocol (MCP) is an open standard introduced by Anthropic to solve the &quot;M x N&quot; integration problem. Anthropic donated it to the Agentic AI Foundation, a Linux Foundation fund, in December 2025.&lt;/p&gt;
&lt;p&gt;In a traditional setup, if you have M AI clients (like Claude, ChatGPT and an internal agent) and N tools (like GitHub, Slack and your internal DB), you build M x N individual integrations.&lt;/p&gt;
&lt;h3&gt;From M x N to M + N&lt;/h3&gt;
&lt;p&gt;MCP changes this to an M + N problem. With a standard &quot;universal plug,&quot; any MCP-compatible AI client can connect to any MCP-compliant server. Think of it as the USB-C of the AI world.&lt;/p&gt;
&lt;p&gt;Instead of writing custom code to explain how to search your database, you host an MCP server that describes its own capabilities. When the agent connects, it &quot;discovers&quot; what the server can do without you hard-coding the instructions.&lt;/p&gt;
&lt;h3&gt;What runs under the hood&lt;/h3&gt;
&lt;p&gt;MCP uses JSON-RPC 2.0. A server can offer tools, resources (like files or data) and prompt templates to the model.&lt;/p&gt;
&lt;p&gt;Since the &lt;code&gt;2026-07-28&lt;/code&gt; spec, the protocol core is stateless request and response. The connection handshake and session IDs are gone, and each request carries its own protocol version and client capabilities.&lt;/p&gt;
&lt;p&gt;If your app needs state across calls, the server hands the model an explicit handle to pass back. I cover what that means in practice in &lt;a href=&quot;https://ansezz.com/blog/stateless-mcp-servers-laravel/&quot;&gt;stateless MCP servers on Laravel&lt;/a&gt;.&lt;/p&gt;

Count the integrations you maintain today: AI clients times tools. If the number is above five or six, sketch which tools would become one MCP server each.

&lt;figure&gt;
&lt;h2&gt;Structural differences: discovery and consumers&lt;/h2&gt;
&lt;p&gt;The core difference between API and MCP lies in who consumes the interface and how they find what they need.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Feature&lt;/th&gt;
&lt;th&gt;Traditional API&lt;/th&gt;
&lt;th&gt;Model Context Protocol (MCP)&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Primary Consumer&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Human Developers&lt;/td&gt;
&lt;td&gt;AI Agents &amp;amp; LLMs&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Discovery&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Manual (Reading Docs)&lt;/td&gt;
&lt;td&gt;Automatic (Self-describing)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Interface&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Heterogeneous (REST/GraphQL)&lt;/td&gt;
&lt;td&gt;Standardized (JSON-RPC)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;State&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Mostly Stateless&lt;/td&gt;
&lt;td&gt;Stateless core since &lt;code&gt;2026-07-28&lt;/code&gt;; explicit handles for app state&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Flexibility&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Rigid / Pre-scripted&lt;/td&gt;
&lt;td&gt;Dynamic / Reasoning-based&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3&gt;Docs for humans, descriptions for models&lt;/h3&gt;
&lt;p&gt;APIs are built for humans to read and implement. You look at a Swagger UI, understand the authentication and write a fetch request.&lt;/p&gt;
&lt;p&gt;MCP is built for models to navigate. An MCP server lists its tools and resources along with natural language descriptions. The model reasons about which tool to call based on the user&apos;s intent.&lt;/p&gt;
&lt;p&gt;If you are &lt;a href=&quot;https://ansezz.com/blog/ai-vs-traditional-development/&quot;&gt;comparing AI vs traditional development&lt;/a&gt;, this is a prime example of the shift. Traditional development builds the pipes. AI engineering with MCP builds the connectors that let the model choose its own pipes.&lt;/p&gt;
&lt;p&gt;Developers read API docs. Models read MCP descriptions.&lt;/p&gt;
&lt;h2&gt;Why AI agents need MCP for scale&lt;/h2&gt;
&lt;p&gt;Agentic systems need a level of autonomy that traditional APIs struggle to provide efficiently.&lt;/p&gt;
&lt;p&gt;An agent asked to &quot;research a company and draft a proposal&quot; might need a search tool, a CRM, a file system and a PDF generator.&lt;/p&gt;
&lt;h3&gt;Less context, fewer wrong choices&lt;/h3&gt;
&lt;p&gt;With standard APIs, you feed the descriptions of all those endpoints into the model&apos;s context window. This eats tokens and raises the risk of the model getting confused.&lt;/p&gt;
&lt;p&gt;With MCP, the client asks the server what it offers (and can cache that list), and the agent calls tools on demand. You can surface only the tools relevant to the task instead of pre-loading every schema.&lt;/p&gt;
&lt;p&gt;The result is less wasted context and fewer irrelevant choices for the model to wade through.&lt;/p&gt;
&lt;h3&gt;Resources that can notify you&lt;/h3&gt;
&lt;p&gt;MCP also defines a &quot;resource&quot; primitive. An API endpoint returns data on request. An MCP resource can be subscribed to, so the server sends a notification when the underlying file or record changes.&lt;/p&gt;
&lt;h3&gt;Lightweight RAG, not a vector store&lt;/h3&gt;
&lt;p&gt;For lightweight retrieval-augmented generation (RAG) cases, an MCP server can expose your local files or database to the model in a standard way. That spares you a custom ingestion layer for every experiment.&lt;/p&gt;
&lt;p&gt;It does not replace a vector store for large-scale semantic search. Get that wrong and you hit the usual &lt;a href=&quot;https://ansezz.com/blog/7-rag-mistakes-production/&quot;&gt;production RAG mistakes&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Implementation: how they work together&lt;/h2&gt;
&lt;p&gt;MCP does not replace APIs. In fact, MCP usually wraps existing APIs. Your business logic, security constraints and data persistence still live in your core services.&lt;/p&gt;
&lt;h3&gt;A Laravel example&lt;/h3&gt;
&lt;p&gt;Say you have a Laravel backend with REST endpoints for managing customer orders.&lt;/p&gt;
&lt;p&gt;To make them accessible to an AI agent, you build a small MCP server (perhaps in Node.js or Python) that sits between the agent and your Laravel API.&lt;/p&gt;
&lt;h3&gt;The translation layer&lt;/h3&gt;
&lt;p&gt;The MCP server describes the &lt;code&gt;get_order_history&lt;/code&gt; tool in a way an LLM understands.&lt;/p&gt;
&lt;p&gt;When the LLM calls that tool through MCP, the server makes the actual REST call to your Laravel backend, receives the JSON and passes the relevant context back to the model.&lt;/p&gt;
&lt;p&gt;This separation lets your core engineering team focus on solid, well-tested APIs while your AI team builds the MCP wrappers that enable agentic behavior.&lt;/p&gt;

  &lt;div&gt;Each AI client gets hand-written function schemas for each endpoint. Change the API and you update every client&apos;s prompt.&lt;/div&gt;
  &lt;div&gt;One MCP server describes the tools and calls your REST API. Every MCP client discovers the change on its next list call.&lt;/div&gt;


Pick one read-only endpoint, like order history, and wrap it as a single MCP tool with a clear one-sentence description. Test it from an MCP client before you expose anything that writes data.

&lt;figure&gt;
&lt;h2&gt;Choosing the right tool for the job&lt;/h2&gt;
&lt;p&gt;When should you stick to direct API calls, and when should you implement MCP? It depends on the complexity of your integrations and the role of the LLM.&lt;/p&gt;
&lt;h3&gt;Use direct APIs when&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;You have a simple request-response flow with no AI reasoning involved.&lt;/li&gt;
&lt;li&gt;You need absolute minimum latency for high-throughput systems.&lt;/li&gt;
&lt;li&gt;You are performing deterministic tasks like processing payments or bulk data migrations.&lt;/li&gt;
&lt;li&gt;You only have one or two integrations that rarely change.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Use MCP when&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;You are building complex agents that need three or more tools.&lt;/li&gt;
&lt;li&gt;Your tools and data sources change frequently.&lt;/li&gt;
&lt;li&gt;You want your tools reusable across different AI clients (e.g., &lt;a href=&quot;https://ansezz.com/blog/claude-mcp-dev-tools/&quot;&gt;Claude Desktop and custom IDE tools&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;You need to expose local data or specialized resources to an LLM without building a custom backend for every experiment.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Where MCP stops&lt;/h3&gt;
&lt;p&gt;One boundary worth drawing early: MCP covers the agent-to-tool axis only. The moment two agents need to delegate work to each other, you are in a different protocol&apos;s territory.&lt;/p&gt;
&lt;p&gt;See &lt;a href=&quot;https://ansezz.com/blog/mcp-vs-a2a-vs-acp/&quot;&gt;MCP vs A2A vs ACP&lt;/a&gt; for how the two layers stack.&lt;/p&gt;

- APIs are the &quot;what&quot; (the data and logic), while MCP is the &quot;how&quot; (how the AI interacts with that data).
- MCP removes the M x N integration problem with a universal protocol for AI tool discovery.
- Traditional APIs suit deterministic software-to-software paths; MCP suits non-deterministic AI-to-tool reasoning.
- Implementing MCP often means wrapping existing REST or GraphQL APIs to make them self-describing for LLMs.
- MCP cuts token waste and prompt complexity by standardizing how context is shared with the model.
- For modern AI engineering, MCP is becoming the standard layer for building agentic workflows that scale.

&lt;p&gt;If you&apos;re wrapping your existing APIs in MCP so agents can use them safely, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams ship it&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;What is the biggest friction point you face when giving your AI agents access to your internal production databases?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>mcp</category><category>api-design</category><category>ai</category><category>llm</category><category>agentic-ai</category><category>architecture</category></item><item><title>Caching for speed: Redis and semantic layers in RAG</title><link>https://ansezz.com/blog/redis-semantic-caching-rag/</link><guid isPermaLink="true">https://ansezz.com/blog/redis-semantic-caching-rag/</guid><description>Stop paying for the same LLM call twice. Two-tier caching with Redis keys and RedisVL semantic lookups slashes RAG latency and trims your LLM API bill.</description><pubDate>Tue, 26 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;The cheapest LLM call is the one you never make. A two-tier Redis cache answers repeat questions in milliseconds and keeps them off your API bill.&lt;/p&gt;

- Put an exact-match cache first (normalized, hashed query keys) and a semantic cache second (RedisVL vector lookup with a strict distance threshold).
- Guard against the semantic trap: version your context, partition by tenant and invalidate on data changes.
- Measure hit rate and semantic precision, and review the borderline hits every week before you loosen the threshold.

&lt;p&gt;You shipped your RAG pipeline. Retrieval is accurate and the LLM is quick. Then you look at your cloud bill and your P99 latency.&lt;/p&gt;
&lt;p&gt;Every query, even &quot;what are your shipping times?&quot; for the tenth time, runs the full chain: embedding, vector search and an expensive LLM call.&lt;/p&gt;
&lt;h3&gt;Paying twice for the same answer&lt;/h3&gt;
&lt;p&gt;At scale you pay for the same computation over and over. Users wait two seconds for answers that could take twenty milliseconds, and your &quot;denial of wallet&quot; risk climbs.&lt;/p&gt;
&lt;p&gt;The fix is a smarter cache. Semantic caching with Redis turns a multi-second chain into a single-digit-millisecond lookup. At the hit rates a busy FAQ bot reaches, it can cut LLM API spend by roughly half. Provider prompt caching saves on a different part, the long prefix you resend on every call, and my &lt;a href=&quot;https://ansezz.com/tools/prompt-caching-calculator/&quot;&gt;prompt caching calculator&lt;/a&gt; shows when that pays off.&lt;/p&gt;
&lt;h2&gt;The two-tier cache&lt;/h2&gt;
&lt;p&gt;Standard caching relies on exact matches. &quot;How do I reset my password?&quot; and &quot;how do i reset my password&quot; can share a key if you normalize the string. &quot;Can you help me change my password?&quot; misses a traditional cache.&lt;/p&gt;
&lt;h3&gt;Tier 1: exact cache&lt;/h3&gt;
&lt;p&gt;A plain key-value entry in Redis. I normalize the query (lowercase, trim, strip punctuation) and hash it. My &lt;a href=&quot;https://ansezz.com/tools/hash-generator/&quot;&gt;SHA hash generator&lt;/a&gt; shows what those keys look like.&lt;/p&gt;
&lt;p&gt;It&apos;s the first line of defense: almost free, with zero false positives.&lt;/p&gt;
&lt;h3&gt;Tier 2: semantic cache&lt;/h3&gt;
&lt;p&gt;If the exact cache misses, I embed the query and look for a close match in a Redis vector index. If a previous question is close enough (a cosine distance of 0.1 or less, about 0.9 similarity), I serve the cached answer instead of calling the LLM.&lt;/p&gt;
&lt;p&gt;You never do the heavy lifting twice for the same intent.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Why Redis for semantic caching&lt;/h2&gt;
&lt;p&gt;Most developers think of Redis as a key-value store. With the &lt;a href=&quot;https://redis.io/blog/how-to-cache-semantic-search/&quot;&gt;Redis Vector Library (RedisVL)&lt;/a&gt;, it also works as a fast vector index.&lt;/p&gt;
&lt;p&gt;Why not use your main vector DB, like Pinecone or Weaviate? Latency.&lt;/p&gt;
&lt;h3&gt;Small index, close to the app&lt;/h3&gt;
&lt;p&gt;Your main vector DB is tuned to search millions of document chunks. The semantic cache is much smaller: recent queries and their answers. Redis usually already sits next to your application, so you skip network hops.&lt;/p&gt;
&lt;p&gt;I typically see Redis vector lookups finish in under 5 ms. An embedding API call takes around 100 ms and an LLM generation around 1,500 ms.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Path&lt;/th&gt;
&lt;th&gt;Typical latency&lt;/th&gt;
&lt;th&gt;LLM cost&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Exact cache hit&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;A few ms&lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Semantic cache hit&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Embedding plus under 5 ms lookup&lt;/td&gt;
&lt;td&gt;None&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Full RAG pipeline&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;1.5 to 2+ seconds&lt;/td&gt;
&lt;td&gt;Full call&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Every cache hit is an LLM call you don&apos;t wait for and don&apos;t pay for.&lt;/p&gt;
&lt;h2&gt;Implementing the semantic layer&lt;/h2&gt;
&lt;p&gt;The key setting is the similarity threshold. Too loose and you give users wrong answers (the &quot;semantic trap&quot;). Too strict and you never get a hit.&lt;/p&gt;
&lt;p&gt;I start with a distance threshold of 0.1. RedisVL measures Redis cosine distance on a 0 to 2 scale, where lower is stricter, so 0.1 is roughly 90% similarity.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;from redisvl.extensions.cache.llm import SemanticCache

# Initialize the cache with a conservative threshold and a 4-hour TTL
llm_cache = SemanticCache(
    name=&quot;production_rag_cache&quot;,
    redis_url=&quot;redis://localhost:6379&quot;,
    distance_threshold=0.1,
    ttl=14400,
)

def answer(query: str) -&amp;gt; str:
    hit = llm_cache.check(prompt=query)
    if hit:
        return hit[0][&quot;response&quot;]

    response = run_rag_pipeline(query)
    llm_cache.store(prompt=query, response=response)
    return response
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This wrapper embeds the incoming query, runs the vector search in Redis and returns the closest cached response when one is within the threshold.&lt;/p&gt;

Export a week of user questions and count exact duplicates after normalizing them. That number is your exact-cache hit rate before you write any semantic code.

&lt;h2&gt;Avoid the semantic trap&lt;/h2&gt;
&lt;p&gt;Semantic caching is useful but risky if you aren&apos;t careful. When your underlying data changes, the cache can keep serving old, wrong answers.&lt;/p&gt;
&lt;h3&gt;Version your context&lt;/h3&gt;
&lt;p&gt;I include a &lt;code&gt;context_version&lt;/code&gt; in cache keys or metadata. When I re-index the product catalog or update the docs, I bump the version. Old entries stop matching and the next request rebuilds them with fresh data.&lt;/p&gt;
&lt;h3&gt;Isolate tenants&lt;/h3&gt;
&lt;p&gt;If User A asks &quot;what is my balance?&quot;, you can&apos;t serve that answer to User B. I partition the cache:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Namespaces:&lt;/strong&gt; &lt;code&gt;cache:tenant_id:query_hash&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Metadata filters:&lt;/strong&gt; add &lt;code&gt;tenant_id&lt;/code&gt; as a filterable field on the vector index.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Semantic matches then only happen inside the right security boundary. My post on &lt;a href=&quot;https://ansezz.com/blog/laravel-multi-tenancy/&quot;&gt;Laravel multi-tenancy&lt;/a&gt; uses the same isolation principles.&lt;/p&gt;

  &lt;div&gt;&quot;What is my balance?&quot; from one tenant matches the cached answer from another tenant. Close in meaning, wrong customer.&lt;/div&gt;
  &lt;div&gt;Every lookup filters on `tenant_id` and the current `context_version`, so a hit can only come from the same tenant and the same data.&lt;/div&gt;

&lt;h2&gt;TTL and staleness&lt;/h2&gt;
&lt;p&gt;In a standard cache you set a 3,600-second expiry and forget it. With a semantic cache I use tiers:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Exact matches:&lt;/strong&gt; 1-hour TTL. Same question, same answer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Semantic matches:&lt;/strong&gt; 4-hour TTL, with a &quot;last validated&quot; timestamp. These cost more to produce, so I keep them longer.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Proactive invalidation:&lt;/strong&gt; when a Shopify product price changes, a Redis worker purges every entry tied to that product ID.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Watch the sliding TTL&lt;/h3&gt;
&lt;p&gt;RedisVL refreshes the TTL on an entry every time &lt;code&gt;check()&lt;/code&gt; matches it. A popular answer can live forever on its own, which is why versioning and proactive invalidation matter more than the TTL.&lt;/p&gt;
&lt;p&gt;I&apos;ve written about similar &lt;a href=&quot;https://ansezz.com/blog/event-driven-pubsub/&quot;&gt;event-driven patterns&lt;/a&gt; for handling these updates at scale.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Measuring success&lt;/h2&gt;
&lt;p&gt;Don&apos;t turn on the cache and walk away. Track two numbers:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Cache hit rate:&lt;/strong&gt; the share of queries Redis answers. I aim for 30 to 50% on general FAQ-style bots.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Semantic precision:&lt;/strong&gt; whether the cached answers are actually correct.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Review the borderline hits&lt;/h3&gt;
&lt;p&gt;I log every semantic hit with its distance. Once a week I sample the hits closest to the threshold (distance between 0.07 and 0.1) and review them by hand. If too many are different questions that only look alike, I tighten the threshold.&lt;/p&gt;

Add the distance score to your semantic hit logs today. Next week, read 20 hits from the band just inside your threshold and mark each one right or wrong.


- **Install `redisvl`** and set up a basic vector index in your dev environment.
- **Look up in two tiers:** exact first, then semantic.
- **Start strict:** a distance threshold of 0.05 to 0.1.
- **Partition and version:** add `tenant_id` and `context_version` to avoid cross-talk and stale answers.
- **Measure:** watch hit rate, precision and your API bill.

&lt;p&gt;For more on production RAG, see &lt;a href=&quot;https://ansezz.com/blog/7-rag-mistakes-production/&quot;&gt;7 RAG mistakes in production&lt;/a&gt; or browse the &lt;a href=&quot;https://ansezz.com/blog/category/architecture/&quot;&gt;architecture archive&lt;/a&gt;. If you want a cache like this in front of your own pipeline, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams cut RAG latency and LLM spend&lt;/a&gt;, or &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;drop me a note&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Which query in your system keeps hitting the LLM when it shouldn&apos;t?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>redis</category><category>ai</category><category>rag</category><category>vector-search</category><category>performance</category><category>infrastructure</category></item><item><title>Smart auto-scaling for modern AI apps</title><link>https://ansezz.com/blog/smart-auto-scaling-ai/</link><guid isPermaLink="true">https://ansezz.com/blog/smart-auto-scaling-ai/</guid><description>CPU auto-scaling fails GPU workloads. Why queue depth, KV-cache pressure, and TTFT beat CPU as triggers, plus the KEDA patterns to scale AI in time.</description><pubDate>Mon, 25 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;When CPU sits at 20% and inference requests time out, your autoscaler is watching the wrong number. Scale AI workloads on queue depth, KV-cache pressure and time to first token.&lt;/p&gt;

- CPU tracks tokenization and HTTP handling; the real work happens on the GPU, so a CPU-based autoscaler stays calm while users wait.
- Waiting requests, KV-cache usage and TTFT are leading signals, and vLLM exports all three as Prometheus metrics you can feed to KEDA.
- Add a forecast for predictable peaks so capacity is warm before the spike, since a new replica can take a minute or more to load model weights.

&lt;p&gt;Your AI app is lagging and users are complaining, but the cloud dashboard says everything is fine. CPU hovers at a comfortable 20% while inference requests time out.&lt;/p&gt;
&lt;h3&gt;The scaling trap&lt;/h3&gt;
&lt;p&gt;Traditional auto-scaling was built for web servers, where CPU and memory are the bottlenecks. For LLM inference, those numbers tell you very little.&lt;/p&gt;
&lt;p&gt;If you wait for CPU to hit 80% before adding a pod, the service is in trouble long before the second instance finishes booting. GPU-bound workloads need a different playbook.&lt;/p&gt;
&lt;h3&gt;Scale on pressure&lt;/h3&gt;
&lt;p&gt;To run a cost-effective AI SaaS, move past reactive hardware metrics. Scale on queue pressure, cache pressure and how fast users get their first token.&lt;/p&gt;
&lt;h2&gt;Why CPU-based auto-scaling misleads you&lt;/h2&gt;
&lt;p&gt;The Kubernetes Horizontal Pod Autoscaler (HPA) is most often set up to watch CPU utilization. For a Laravel or Node.js API, that works: more requests mean more CPU cycles.&lt;/p&gt;
&lt;h3&gt;The work moved to the GPU&lt;/h3&gt;
&lt;p&gt;AI models are different. The CPU handles tokenization, request routing and HTTP headers. The heavy lifting happens on the GPU.&lt;/p&gt;
&lt;p&gt;I&apos;ve seen production clusters where the GPU is pinned at 100% while the CPU sits idle. The autoscaler sees low CPU, decides the pods are fine and never adds a replica, while the queue keeps growing.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;GPU utilization vs occupancy&lt;/h2&gt;
&lt;p&gt;When you start monitoring GPUs, you meet two confusing metrics: utilization and occupancy.&lt;/p&gt;
&lt;h3&gt;Utilization is a duty cycle&lt;/h3&gt;
&lt;p&gt;GPU utilization is the percentage of time the GPU was running work during a sample period. It lags. By the time it reads 90%, your request queue may have been building for a while.&lt;/p&gt;
&lt;h3&gt;Occupancy is finer-grained&lt;/h3&gt;
&lt;p&gt;Occupancy measures how many warps are active on each streaming multiprocessor (SM) compared with the maximum. You can have high utilization and low occupancy if your batch size is too small.&lt;/p&gt;
&lt;p&gt;For scaling, treat utilization as a baseline and look at what happens before a request even reaches the GPU.&lt;/p&gt;
&lt;h2&gt;Queue depth: your best leading indicator&lt;/h2&gt;
&lt;p&gt;To stop fires before they start, watch queue depth. In vLLM it&apos;s the number of requests waiting for a slot in the engine, exported as &lt;code&gt;vllm:num_requests_waiting&lt;/code&gt;. SGLang exposes a similar metric.&lt;/p&gt;
&lt;h3&gt;Scale before latency climbs&lt;/h3&gt;
&lt;p&gt;Queue depth predicts latency. If your model handles 16 concurrent requests before P99 latency starts to climb, set the scaling trigger at 12. To get a real P99 from your own response times, paste them into my &lt;a href=&quot;https://ansezz.com/tools/percentile-calculator/&quot;&gt;latency percentile calculator&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Scaling on queue depth adds capacity while the current hardware is still inside your SLO. That buys the head start you need to pull a fresh container and load 20 GB of model weights into GPU memory.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Signal&lt;/th&gt;
&lt;th&gt;vLLM metric&lt;/th&gt;
&lt;th&gt;What it tells you&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Waiting requests&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;vllm:num_requests_waiting&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Work is piling up before the engine&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;KV-cache usage&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;vllm:kv_cache_usage_perc&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;How close you are to preemptions&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Preemptions&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;vllm:num_preemptions&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Requests are being evicted and recomputed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Time to first token&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;&lt;code&gt;vllm:time_to_first_token_seconds&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;What users feel when they hit enter&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;CPU utilization&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;(node metric)&lt;/td&gt;
&lt;td&gt;Tokenization and HTTP load, rarely the bottleneck&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;In Prometheus, the counter shows up as &lt;code&gt;vllm:num_preemptions_total&lt;/code&gt; and the TTFT histogram as &lt;code&gt;vllm:time_to_first_token_seconds_bucket&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Watch the line of waiting requests. It moves before the chip looks busy.&lt;/p&gt;

Graph `vllm:num_requests_waiting` next to your P99 latency for one busy day. Find the queue length where latency starts to climb, and set your scale-out threshold about 25% below it.

&lt;h2&gt;Token velocity and the KV cache&lt;/h2&gt;
&lt;p&gt;In generative AI, requests vary a lot in size. A 10-token summary is light. A 4,000-token RAG analysis is heavy.&lt;/p&gt;
&lt;h3&gt;When the cache fills up&lt;/h3&gt;
&lt;p&gt;The KV cache is the GPU memory that stores attention keys and values for in-flight sequences. When it&apos;s nearly full, the engine preempts a request to free blocks.&lt;/p&gt;
&lt;p&gt;In vLLM V1, the default preemption mode is recompute: the evicted request&apos;s cache is dropped, and its prompt plus generated tokens are processed again when it resumes. Latency jumps, and P99 starts to look like a mountain range.&lt;/p&gt;
&lt;h3&gt;Scale on two numbers&lt;/h3&gt;
&lt;p&gt;I recommend scaling on a combination of:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Token velocity:&lt;/strong&gt; total tokens per second across all active instances.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;KV-cache pressure:&lt;/strong&gt; the share of cache blocks in use (&lt;code&gt;vllm:kv_cache_usage_perc&lt;/code&gt;).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;When the cache is full, low GPU utilization doesn&apos;t help. You can&apos;t fit more work on that chip, so you add replicas.&lt;/p&gt;

  &lt;div&gt;The HPA watches CPU at 20% and does nothing. The KV cache fills, requests get preempted and recomputed, and TTFT climbs past two seconds.&lt;/div&gt;
  &lt;div&gt;KEDA watches waiting requests and KV-cache usage. A new replica starts loading weights while the current one is still inside its TTFT target.&lt;/div&gt;

&lt;h2&gt;Predictive scaling with ARIMA&lt;/h2&gt;
&lt;p&gt;Reactive scaling always plays catch-up. Even with fast boots, there&apos;s a delay. For apps with predictable traffic, I use ARIMA (Auto-Regressive Integrated Moving Average) models to forecast load.&lt;/p&gt;
&lt;h3&gt;Warm before the spike&lt;/h3&gt;
&lt;p&gt;If traffic always spikes at 9:00 am on Mondays, I don&apos;t wait for the queue to grow. A time-series forecast brings up the base-load pods at 8:55 am.&lt;/p&gt;
&lt;p&gt;You still pay for what you use, and the capacity is there before the first user clicks &quot;Generate.&quot;&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Practical steps for your stack&lt;/h2&gt;
&lt;p&gt;Here is how I structure it:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Use KEDA.&lt;/strong&gt; The Kubernetes Event-Driven Autoscaler can scale on Prometheus queries, like waiting requests or P99 latency, instead of CPU alone.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Set TTFT SLOs.&lt;/strong&gt; Time to first token shapes how fast the app feels. If TTFT P99 passes 500 ms, you need more replicas.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use a composite signal.&lt;/strong&gt; Don&apos;t rely on one metric. Combine queue depth, cache pressure and GPU utilization. Once you have several replicas, route with &lt;a href=&quot;https://ansezz.com/blog/gpu-aware-load-balancing/&quot;&gt;GPU-aware load balancing&lt;/a&gt; so traffic lands on the least-loaded GPU.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Check your RAG pipeline.&lt;/strong&gt; Sometimes the scaling issue is a retrieval issue. Slow vector search makes the engine wait and holds GPU slots. These &lt;a href=&quot;https://ansezz.com/blog/7-rag-mistakes-production/&quot;&gt;common RAG mistakes&lt;/a&gt; help you rule out an upstream bottleneck.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Handle retries in the app.&lt;/strong&gt; For Shopify apps or custom SaaS, make sure your &lt;a href=&quot;https://ansezz.com/blog/agentic-workflows-vibe-coding/&quot;&gt;agentic workflows&lt;/a&gt; retry gracefully while capacity scales up.&lt;/li&gt;
&lt;/ul&gt;

Write a KEDA ScaledObject with a Prometheus trigger on `vllm:num_requests_waiting`, apply it in staging and run a load test. Compare how long it takes to add a replica against your current CPU-based HPA.


- **CPU is the wrong trigger** for GPU inference. Watch the queue and the cache.
- **Queue depth leads latency.** Scale before your SLO breaks, not after.
- **KV-cache pressure** predicts preemptions and the latency spikes they cause.
- **Use KEDA** to scale on vLLM&apos;s Prometheus metrics, and track TTFT as the user-facing SLO.
- **Forecast known peaks** so replicas finish loading weights before traffic arrives.

&lt;p&gt;Smarter triggers save money on idle GPUs and spare your users the &quot;thinking...&quot; spinner. If you&apos;re running inference on Kubernetes, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams scale AI workloads on the right signals&lt;/a&gt;, or &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;drop me a note&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Are you still scaling on CPU, or have you moved to queue-based triggers yet?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>scaling</category><category>ai</category><category>llm</category><category>kubernetes</category><category>llm-inference</category><category>infrastructure</category></item><item><title>GPU-aware load balancing for AI inference</title><link>https://ansezz.com/blog/gpu-aware-load-balancing/</link><guid isPermaLink="true">https://ansezz.com/blog/gpu-aware-load-balancing/</guid><description>Round-robin breaks when LLM requests span 50 to 50,000 tokens. GPU-aware load balancing with prefill/decode disaggregation and the metrics that cut P99.</description><pubDate>Sun, 24 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Your load balancer says CPU is at 40% and everything is fine. Your GPUs are maxed out and your P99 latency is in the gutter.&lt;/p&gt;

- LLM requests vary wildly in weight, so round-robin and CPU metrics hide where the real load is.
- Prefill (reading the prompt) is compute-bound and decode (writing tokens) is memory-bound, so they compete when mixed on one GPU.
- Route on token queue depth, KV cache use, TTFT and inter-token latency, and send shared prefixes to the GPU that already has them cached.

&lt;p&gt;You just scaled your RAG application to a hundred concurrent users. Suddenly, your latency spikes.&lt;/p&gt;
&lt;p&gt;Some users get their answers in two seconds, while others stare at a loading spinner for thirty. This is the problem GPU-aware load balancing exists to solve.&lt;/p&gt;
&lt;h3&gt;Models are not web servers&lt;/h3&gt;
&lt;p&gt;You are treating your AI models like traditional web servers. Sending a 4,000-token prompt to the same GPU that is generating a 50-token summary is a recipe for disaster.&lt;/p&gt;
&lt;p&gt;Round-robin routing is a relic of the past for LLM inference. If you don&apos;t account for how GPUs handle compute and memory, you waste money and hurt your user experience at the same time.&lt;/p&gt;
&lt;h3&gt;More GPUs won&apos;t fix it alone&lt;/h3&gt;
&lt;p&gt;The fix is a load balancer that understands what is happening inside the model. That means GPU-aware routing, prefill vs decode disaggregation, and treating your KV cache as one of the most valuable assets in your stack.&lt;/p&gt;
&lt;h2&gt;Why round-robin is a trap for LLMs&lt;/h2&gt;
&lt;p&gt;In traditional software, a request is a request. Whether it&apos;s a &lt;code&gt;GET /users&lt;/code&gt; or a &lt;code&gt;POST /orders&lt;/code&gt;, the variance in resource use is usually small and predictable.&lt;/p&gt;
&lt;p&gt;Standard load balancers like Nginx or HAProxy work great here. They look at basic health checks and send traffic to the next available worker.&lt;/p&gt;
&lt;h3&gt;Requests have very different weights&lt;/h3&gt;
&lt;p&gt;AI is different. One user might ask &quot;what is 2+2?&quot; while another uploads a 50-page PDF and asks for a deep analysis.&lt;/p&gt;
&lt;p&gt;If your load balancer sends both to the same GPU, the heavy request hogs the compute, and the light request waits in a queue.&lt;/p&gt;
&lt;h3&gt;CPU metrics tell you nothing&lt;/h3&gt;
&lt;p&gt;A GPU can be at 100% utilization while doing very different types of work. Some work is compute-bound and needs raw processing power.&lt;/p&gt;
&lt;p&gt;Other work is memory-bound, limited by how fast data moves in and out of VRAM. To route well, you have to look inside the inference lifecycle.&lt;/p&gt;
&lt;h2&gt;Prefill vs decode: the performance gap&lt;/h2&gt;
&lt;p&gt;LLM inference happens in two distinct phases. Understanding the difference is the &quot;aha!&quot; moment for GPU load balancing.&lt;/p&gt;
&lt;h3&gt;Prefill: read the whole prompt&lt;/h3&gt;
&lt;p&gt;In &lt;strong&gt;prefill&lt;/strong&gt;, the model reads your entire prompt and processes all the tokens at once. It is a heavy, compute-intensive task that builds the &lt;strong&gt;KV cache&lt;/strong&gt; (key-value cache).&lt;/p&gt;
&lt;p&gt;Prefill loves big batches and fast tensor cores. It is where the heavy lifting happens.&lt;/p&gt;
&lt;h3&gt;Decode: one token at a time&lt;/h3&gt;
&lt;p&gt;In &lt;strong&gt;decode&lt;/strong&gt;, the model generates the response one token at a time. Each new token only needs the previous tokens and the KV cache.&lt;/p&gt;
&lt;p&gt;This phase is light on compute but very heavy on memory bandwidth. It is slow and long-lived.&lt;/p&gt;
&lt;h3&gt;Why mixing them hurts&lt;/h3&gt;
&lt;p&gt;When you mix the two on one GPU without a smart scheduler, the prefill of a new request often pauses the decode of existing requests. That causes the jittery, stuttering text users hate.&lt;/p&gt;
&lt;p&gt;GPU-aware load balancing lets you treat these phases differently across your fleet.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Phase&lt;/th&gt;
&lt;th&gt;What it does&lt;/th&gt;
&lt;th&gt;Bound by&lt;/th&gt;
&lt;th&gt;Metric to watch&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Prefill&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Reads the full prompt at once&lt;/td&gt;
&lt;td&gt;Compute&lt;/td&gt;
&lt;td&gt;Time to first token (TTFT)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Decode&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Writes the answer token by token&lt;/td&gt;
&lt;td&gt;Memory bandwidth&lt;/td&gt;
&lt;td&gt;Inter-token latency (ITL)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;figure&gt;
&lt;h2&gt;Metrics for the real world&lt;/h2&gt;
&lt;p&gt;To build a better router, stop looking at CPU and start looking at these four metrics:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Token queue depth:&lt;/strong&gt; how many tokens are waiting to be processed? This shows &quot;load&quot; far better than request counts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;KV cache utilization:&lt;/strong&gt; GPUs have limited VRAM, and the KV cache holds the &quot;memory&quot; of ongoing conversations. If a GPU&apos;s VRAM is 90% full of KV cache, it cannot accept a large new prompt, even if it looks &quot;idle.&quot;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Time to first token (TTFT):&lt;/strong&gt; the latency of the prefill phase. If TTFT is climbing, your prefill pool is congested.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Inter-token latency (ITL):&lt;/strong&gt; the speed of the decode phase. If this is high, your GPUs are likely limited by memory bandwidth.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Get the numbers from your engine&lt;/h3&gt;
&lt;p&gt;I often recommend tools like &lt;a href=&quot;https://github.com/vllm-project/vllm&quot;&gt;vLLM&lt;/a&gt; because they expose these metrics out of the box.&lt;/p&gt;
&lt;p&gt;You can pipe them into a custom gateway that routes on real-time VRAM availability instead of a simple &quot;is the server up?&quot; check.&lt;/p&gt;

Scrape TTFT, inter-token latency and KV cache usage from one inference node and put them on a single dashboard next to your P99. Watch which one moves first when latency spikes.

&lt;h2&gt;Prefix-aware routing: reuse the KV cache&lt;/h2&gt;
&lt;p&gt;The most expensive part of a RAG request is often re-processing the same system prompt or long context again and again.&lt;/p&gt;
&lt;p&gt;If you send five follow-up questions about the same document to five different GPUs, each GPU runs prefill for that document from scratch. On hosted APIs, prompt caching attacks the same cost, and my &lt;a href=&quot;https://ansezz.com/tools/llm-cost-calculator/&quot;&gt;LLM cost calculator&lt;/a&gt; shows the effect on your monthly bill.&lt;/p&gt;
&lt;h3&gt;Send the prompt where the cache is warm&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;Prefix-aware routing&lt;/strong&gt; (also called KV-cache-aware routing) fixes this. Your load balancer tokenizes the start of the prompt and looks for a GPU that already has that content in its KV cache.&lt;/p&gt;
&lt;p&gt;Matching the prefix lets you skip prefill for the shared part and reuse the cached keys and values directly. That can turn hundreds of milliseconds of TTFT into a near-instant first token.&lt;/p&gt;
&lt;p&gt;Every repeated prefill is a GPU redoing work it already finished somewhere else.&lt;/p&gt;
&lt;h3&gt;A common RAG blind spot&lt;/h3&gt;
&lt;p&gt;This is one of the most effective optimizations in a production RAG system. I&apos;ve written before about &lt;a href=&quot;https://ansezz.com/blog/7-rag-mistakes-production/&quot;&gt;common RAG mistakes&lt;/a&gt;, and ignoring cache locality is one of them.&lt;/p&gt;
&lt;p&gt;For the layer above this (caching whole responses and embeddings), see &lt;a href=&quot;https://ansezz.com/blog/redis-semantic-caching-rag/&quot;&gt;Redis and semantic caching for RAG&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Splitting the fleet into specialized pools&lt;/h2&gt;
&lt;p&gt;As you scale, stop treating every GPU as a generalist. Build &lt;strong&gt;disaggregated inference fleets&lt;/strong&gt; instead.&lt;/p&gt;
&lt;p&gt;I like to split my GPUs into two pools:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;The prefill pool:&lt;/strong&gt; compute-heavy GPUs (like H100s or B200s) tuned to chew through large prompts fast. These nodes process the initial context, then hand off the KV state.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The decode pool:&lt;/strong&gt; GPUs sized for memory bandwidth and capacity rather than raw FLOPs (think A100s or H200s) that focus on producing tokens for existing requests.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Scale the pool your users stress&lt;/h3&gt;
&lt;p&gt;If your users upload huge documents but ask for short summaries, scale your prefill pool. If they have long, chatty conversations, scale your decode pool.&lt;/p&gt;
&lt;p&gt;This is the same logic used in &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;modern DevOps with Coolify&lt;/a&gt;. You wouldn&apos;t put your heavy database on the same tiny instance as your frontend, so why mix heavy prefill work with light decode work?&lt;/p&gt;

  &lt;div&gt;Every GPU does prefill and decode. New long prompts pause ongoing answers, and you can only scale everything at once.&lt;/div&gt;
  &lt;div&gt;Prefill GPUs read prompts and hand off the KV state. Decode GPUs keep streaming tokens, and you scale each pool for the load it actually gets.&lt;/div&gt;

&lt;figure&gt;
&lt;h2&gt;Implementing your first GPU-aware router&lt;/h2&gt;
&lt;p&gt;You don&apos;t need to build a custom engine from scratch. Here is the practical path I follow when setting this up for a new SaaS:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Centralize your metrics:&lt;/strong&gt; use Prometheus to scrape vLLM or TGI metrics from every GPU node.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Use a smart gateway:&lt;/strong&gt; write a middleware in Go or Rust (or even a heavy-duty Lua script in OpenResty) that checks these metrics before choosing a target.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Prioritize KV cache:&lt;/strong&gt; route on prefix overlap when you can. A cheap first approximation is session stickiness: if a node served this &lt;code&gt;conversation_id&lt;/code&gt; recently and isn&apos;t at 100% KV utilization, send the follow-up there so the warm cache gets reused.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Set hard limits:&lt;/strong&gt; if a GPU reaches 85% VRAM usage, take it out of the rotation for new prompts until some sessions finish.&lt;/li&gt;
&lt;/ol&gt;

Add session stickiness on `conversation_id` to your gateway, with a fallback to the least-loaded node when the sticky one is above your VRAM limit.

&lt;h3&gt;From black box to context-aware&lt;/h3&gt;
&lt;p&gt;Managing AI compute means moving from &quot;black box&quot; infrastructure to &quot;context-aware&quot; infrastructure. When your load balancer knows the difference between a 10-token greeting and a 10,000-token context window, your costs go down and your users stay happy.&lt;/p&gt;
&lt;p&gt;It&apos;s easy to get lost in the hype of &quot;agentic systems&quot; and &lt;a href=&quot;https://ansezz.com/blog/mcp-context-aware-agents/&quot;&gt;context-aware agents&lt;/a&gt;, but none of that matters if your infrastructure is buckling under unoptimized routing.&lt;/p&gt;

- **Round-robin fails for LLMs** because request weight varies from a few tokens to whole documents.
- **Prefill is compute-bound, decode is memory-bound.** Mixing them on one GPU causes stutter.
- **Route on token queue depth, KV cache use, TTFT and ITL,** not CPU.
- **Prefix-aware routing reuses the KV cache** and cuts time to first token.
- **Split prefill and decode pools** so you can scale each for your real workload.

&lt;p&gt;If round-robin is hurting your inference latency, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams build GPU-aware routing for LLM serving&lt;/a&gt;, or drop a note via &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;contact&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If you are still using round-robin for your AI models, what is the main bottleneck you are seeing in your P99 latency right now?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>llm-inference</category><category>networking</category><category>ai</category><category>llm</category><category>infrastructure</category></item><item><title>Circuit breakers: stopping vector DB failures</title><link>https://ansezz.com/blog/circuit-breakers-vector-db/</link><guid isPermaLink="true">https://ansezz.com/blog/circuit-breakers-vector-db/</guid><description>A slow vector DB kills SaaS faster than a dead one. The circuit-breaker pattern for AI infra: states, fallback tiers, and Laravel-friendly wiring.</description><pubDate>Sat, 23 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A slow vector database can take your whole app down without ever going offline. A circuit breaker is the switch that stops that from happening.&lt;/p&gt;

- In production, a slow dependency is often more dangerous than a dead one, because waiting requests eat your workers, memory and connections.
- A circuit breaker has three states (closed, open, half-open) and fails fast once a failure threshold is hit, so the struggling service can recover.
- Pair the breaker with fallbacks (keyword search, a Redis cache, LLM-only mode) and monitor how often it trips.

&lt;p&gt;You built a beautiful RAG pipeline. It works perfectly on your machine with a few hundred vectors. Then you launch, traffic spikes and your managed vector database starts sweating.&lt;/p&gt;
&lt;p&gt;A similarity search that used to take 50ms now takes 5 seconds. Your web workers are all tied up waiting for responses that aren&apos;t coming.&lt;/p&gt;
&lt;h3&gt;Slow is the new down&lt;/h3&gt;
&lt;p&gt;The database isn&apos;t technically down, but it is slow enough to kill your entire application. Your users see spinning loaders until the request finally times out.&lt;/p&gt;
&lt;p&gt;This is a classic cascading failure (the kind a circuit breaker exists to stop), and it is the fastest way to drain your &quot;innovation budget&quot; and your users&apos; patience.&lt;/p&gt;
&lt;h3&gt;Why waiting hurts&lt;/h3&gt;
&lt;p&gt;We often treat external APIs and databases as if they are always healthy. We write code that assumes the vector DB will return results. When it doesn&apos;t, we wait, and while we wait we hold onto memory and CPU cycles.&lt;/p&gt;
&lt;p&gt;The fix is an old-school electrical engineering concept applied to software: the circuit breaker. This guide shows you how to wrap your AI infrastructure in protective logic so a slow dependency doesn&apos;t take your whole SaaS down with it.&lt;/p&gt;
&lt;h2&gt;How the circuit breaker pattern works&lt;/h2&gt;
&lt;p&gt;The circuit breaker pattern is a state machine that sits between your application code and your external service.&lt;/p&gt;
&lt;p&gt;The idea comes straight out of Michael Nygard&apos;s &lt;em&gt;Release It!&lt;/em&gt;. It monitors every call you make and has three states that dictate how it handles traffic.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;State&lt;/th&gt;
&lt;th&gt;What happens to calls&lt;/th&gt;
&lt;th&gt;Moves on when&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Closed&lt;/td&gt;
&lt;td&gt;Calls flow through while the breaker counts failures&lt;/td&gt;
&lt;td&gt;The failure threshold is hit, then it opens&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Open&lt;/td&gt;
&lt;td&gt;Calls fail fast or get a fallback, no network call&lt;/td&gt;
&lt;td&gt;The cooldown ends, then it goes half-open&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Half-open&lt;/td&gt;
&lt;td&gt;A few test calls go through&lt;/td&gt;
&lt;td&gt;Tests pass (closed) or fail (open again)&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3&gt;Closed: the healthy state&lt;/h3&gt;
&lt;p&gt;In the closed state, the circuit is complete. Requests flow through to your vector database or LLM provider normally.&lt;/p&gt;
&lt;p&gt;The breaker is silently watching. It keeps a count of how many requests failed or took too long. As long as the failure rate stays below your threshold, it stays closed. This is the &quot;everything is fine&quot; mode.&lt;/p&gt;
&lt;h3&gt;Open: the fail-fast state&lt;/h3&gt;
&lt;p&gt;Once the failure threshold is hit (say 50% of requests failed in the last 30 seconds), the breaker &quot;trips&quot; and moves to the open state.&lt;/p&gt;
&lt;p&gt;Now every call to the vector DB immediately throws an error or returns a fallback response, without even attempting the network call. This gives your database room to breathe and recover, and your application stops wasting time on a service that is clearly struggling.&lt;/p&gt;
&lt;h3&gt;Half-open: the recovery test&lt;/h3&gt;
&lt;p&gt;After a cooldown period, the breaker moves to the half-open state and lets a small number of &quot;test&quot; requests through.&lt;/p&gt;
&lt;p&gt;If these test calls succeed, the breaker assumes the service is healthy again and moves back to closed. If they fail, it goes straight back to open for another cooldown cycle. This is a controlled way to probe the system before fully re-engaging.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Why your RAG pipeline needs this&lt;/h2&gt;
&lt;p&gt;RAG pipelines are particularly vulnerable because they usually involve several high-latency network hops. You embed the query, search the vector DB, then call the LLM. If any of these pieces fail or slow down, the whole experience breaks.&lt;/p&gt;
&lt;h3&gt;Hard errors are the easy part&lt;/h3&gt;
&lt;p&gt;Most developers only handle hard errors like a &lt;code&gt;404&lt;/code&gt; or a &lt;code&gt;500&lt;/code&gt; status code. But in production, &quot;slow&quot; is often more dangerous than &quot;down.&quot;&lt;/p&gt;
&lt;p&gt;A slow vector DB creates a bottleneck that backs up your entire request queue. By the time you notice, your server is out of memory because it is holding open thousands of connections.&lt;/p&gt;
&lt;p&gt;A dead service fails fast. A slow one quietly holds every worker hostage.&lt;/p&gt;
&lt;p&gt;If you have read my post on &lt;a href=&quot;https://ansezz.com/blog/7-rag-mistakes-production/&quot;&gt;7 RAG mistakes in production&lt;/a&gt;, you know that reliability is the difference between a demo and a product. The circuit breaker is your insurance policy against these outages.&lt;/p&gt;

List every external call in one RAG request (embedding API, vector DB, LLM) and write down its current timeout. Any call with no timeout, or one longer than your page budget, is your first breaker candidate.

&lt;h2&gt;Implementing fallback strategies&lt;/h2&gt;
&lt;p&gt;Tripping the breaker shouldn&apos;t always mean showing an error message to the user. Good AI systems use fallbacks to keep some level of service even when parts of the stack are failing.&lt;/p&gt;
&lt;h3&gt;Hot and cold tiers&lt;/h3&gt;
&lt;p&gt;Think of your vector DB as your &quot;hot&quot; knowledge tier. If it fails, you should have a &quot;cold&quot; fallback, such as a standard keyword search in your primary Postgres or MySQL database.&lt;/p&gt;
&lt;p&gt;The results might be less relevant than a vector search, but a &quot;decent&quot; answer is always better than a &quot;timed out&quot; error.&lt;/p&gt;
&lt;h3&gt;Cached responses&lt;/h3&gt;
&lt;p&gt;Another strong strategy is &lt;a href=&quot;https://ansezz.com/blog/redis-semantic-caching-rag/&quot;&gt;semantic caching with Redis&lt;/a&gt;. If the circuit is open, check the cache for similar queries that were answered recently.&lt;/p&gt;
&lt;p&gt;Even if you can&apos;t generate a fresh answer, you might be able to serve a cached one. This keeps the user moving while your backend recovers.&lt;/p&gt;
&lt;h3&gt;LLM-only mode&lt;/h3&gt;
&lt;p&gt;If retrieval is what&apos;s failing, you can still send the user&apos;s prompt to the LLM with a note that external knowledge is currently unavailable. The LLM then answers from its general training data.&lt;/p&gt;
&lt;p&gt;It is a degraded experience, but it still works. Be open about it: tell the user that &quot;live&quot; data isn&apos;t available so they know to verify the response.&lt;/p&gt;

  &lt;div&gt;Every request waits on the slow vector DB until it times out. Workers pile up, memory climbs and the whole app stalls.&lt;/div&gt;
  &lt;div&gt;After the threshold, calls fail fast to keyword search, a cached answer or LLM-only mode. The app stays up while the DB recovers.&lt;/div&gt;


Pick one fallback for your RAG endpoint today, even if it is only a keyword search over the same table, and write the message the user sees when it is active.

&lt;h2&gt;Building it in Laravel&lt;/h2&gt;
&lt;p&gt;Since I spend a lot of time in the Laravel ecosystem, I lean on patterns that make this easy. You don&apos;t need to write the state machine from scratch.&lt;/p&gt;
&lt;p&gt;A community package like &lt;code&gt;ackintosh/ganesha&lt;/code&gt; (a PHP circuit breaker), or a small custom wrapper around the &lt;code&gt;illuminate/http&lt;/code&gt; client with a Redis-backed failure counter, gets the job done.&lt;/p&gt;
&lt;h3&gt;Wrap the client, catch the open state&lt;/h3&gt;
&lt;p&gt;The goal is to wrap your API calls in a block that understands these states. When you call your vector DB client, you wrap it in the breaker. If the call fails several times, the breaker trips.&lt;/p&gt;
&lt;p&gt;In the &lt;code&gt;catch&lt;/code&gt; block, you handle the &lt;code&gt;CircuitBreakerOpenException&lt;/code&gt; by returning your fallback data. This keeps your controllers clean and the failure handling in one place.&lt;/p&gt;
&lt;h3&gt;Keep health checks honest&lt;/h3&gt;
&lt;p&gt;You can also pair this with your &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;SaaS hosting on Coolify&lt;/a&gt; so your containers don&apos;t get killed by health checks just because an external API is slow. The breaker prevents the resource bloat that usually triggers those health-check failures.&lt;/p&gt;
&lt;h2&gt;Live telemetry and smart routing&lt;/h2&gt;
&lt;p&gt;Don&apos;t set a circuit breaker and walk away. Monitor it. You need live telemetry to see how often your circuits trip, and tools like Prometheus (or even simple logs piped to a dashboard) can tell you a lot.&lt;/p&gt;
&lt;h3&gt;Route around the failing region&lt;/h3&gt;
&lt;p&gt;If your primary vector DB in &lt;code&gt;us-east-1&lt;/code&gt; keeps tripping but your secondary in &lt;code&gt;eu-west-1&lt;/code&gt; is healthy, you can add smart routing. The breaker can act as a signal to your &lt;a href=&quot;https://ansezz.com/blog/gpu-aware-load-balancing/&quot;&gt;load balancer&lt;/a&gt; or internal router to shift traffic to the healthy region.&lt;/p&gt;
&lt;p&gt;This kind of &lt;a href=&quot;https://ansezz.com/blog/event-driven-pubsub/&quot;&gt;event-driven architecture&lt;/a&gt; makes your system self-healing. It doesn&apos;t wait for a human to wake up at 3am. It detects the failure, trips the breaker, uses the fallback and tries to recover on its own.&lt;/p&gt;
&lt;figure&gt;

Add an alert that fires when any circuit stays open for more than a few minutes. That usually means a real provider outage, and it is the one alert worth waking up for.

&lt;h2&gt;Practical steps to get started&lt;/h2&gt;
&lt;p&gt;If you are ready to harden your AI infrastructure, start here:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Identify your weakest links.&lt;/strong&gt; List every external call in your RAG pipeline. Usually it is the embedding API and the vector DB.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Define your thresholds.&lt;/strong&gt; How many slow requests will you tolerate? Start with a 50% failure rate over 30 seconds and a 2-second timeout.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Choose your fallbacks.&lt;/strong&gt; Decide what happens when the breaker is open: an error, a cache or keyword search.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Wrap your clients.&lt;/strong&gt; Use a library to wrap your HTTP or database calls. Don&apos;t build the state machine yourself unless you have a very specific use case.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Monitor the trips.&lt;/strong&gt; Alert when a circuit stays open for more than a few minutes. This usually means a major provider outage that needs your attention.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The goal is to fail gracefully. Every system has issues, but the ones that survive don&apos;t let a small fire in a dependency burn down the whole house.&lt;/p&gt;

- Treat &quot;slow&quot; as a failure, not only `500` errors.
- Closed, open, half-open: fail fast once the threshold is hit, then probe before you trust the service again.
- Always have a fallback: keyword search, a cached answer or LLM-only mode with an honest notice.
- Use a library such as `ackintosh/ganesha` instead of writing the state machine yourself.
- Monitor trips and alert when a circuit stays open.

&lt;p&gt;If your RAG stack stalls every time the vector database slows down, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams add circuit breakers and fallbacks to AI infrastructure&lt;/a&gt;, or reach out through &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;contact&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Have you ever had a slow dependency take down your entire application, or are you still relying on long timeouts and luck?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>observability</category><category>ai</category><category>rag</category><category>vector-search</category><category>laravel</category><category>infrastructure</category></item><item><title>Message queues for heavy-duty document processing</title><link>https://ansezz.com/blog/message-queues-document-processing/</link><guid isPermaLink="true">https://ansezz.com/blog/message-queues-document-processing/</guid><description>Stop running embeddings in the request cycle. Build a document pipeline on message queues with staged workers, retries, dead-letter queues, and autoscaling.</description><pubDate>Fri, 22 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;If your embeddings run inside the request cycle, the first 50MB PDF will take your app down. Put that work behind a queue.&lt;/p&gt;

- Document processing (OCR, extraction, chunking, embedding) is slow and unpredictable, so it belongs in background workers, not web requests.
- Split the pipeline into queued stages with explicit retries, exponential backoff and a dead-letter queue for files that can never succeed.
- Batch embedding calls, keep messages small and idempotent, and scale workers on queue depth instead of CPU.

&lt;p&gt;If you run document embeddings inside your request-response cycle instead of behind a message queue, you are playing with fire.&lt;/p&gt;
&lt;p&gt;I have seen many developers build a beautiful RAG application that falls over the second a user uploads a 50MB PDF. The browser spins, the proxy timeout hits and the database locks up while your worker tries to chunk 500 pages of legal jargon in real time.&lt;/p&gt;
&lt;h3&gt;The heavy lifting problem&lt;/h3&gt;
&lt;p&gt;This is the classic &quot;heavy lifting&quot; problem in AI engineering. Document processing (OCR, text extraction, semantic chunking and embedding) is slow, unpredictable and resource-heavy.&lt;/p&gt;
&lt;p&gt;Forcing it into a synchronous web request gives you a bad user experience and a fragile system.&lt;/p&gt;
&lt;h3&gt;Decouple it&lt;/h3&gt;
&lt;p&gt;The fix is decoupling with message queues. Here is why async work belongs in a queue and how to build an ingestion pipeline that doesn&apos;t melt your server.&lt;/p&gt;
&lt;p&gt;If you want the broker-level foundations first, I cover them in &lt;a href=&quot;https://ansezz.com/blog/scaling-with-rabbitmq/&quot;&gt;scaling with RabbitMQ&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;The synchronous trap&lt;/h2&gt;
&lt;p&gt;Imagine a user uploads a document to your SaaS. Your code receives the file, sends it to an extraction API and waits.&lt;/p&gt;
&lt;p&gt;Then it loops through the text to create chunks, sends each chunk to an embedding model and finally saves it all to pgvector.&lt;/p&gt;
&lt;h3&gt;Where it breaks&lt;/h3&gt;
&lt;p&gt;If the whole chain runs long, you hit a timeout somewhere: a proxy gateway timeout (Nginx defaults to 60s), a PHP &lt;code&gt;max_execution_time&lt;/code&gt; or a platform request cap. The connection drops.&lt;/p&gt;
&lt;p&gt;If the embedding API has a momentary blip, the whole process fails and the user has to start over. While your server is busy with this heavy work, it isn&apos;t responding to other users.&lt;/p&gt;
&lt;h3&gt;The 100ms rule&lt;/h3&gt;
&lt;p&gt;A good rule of thumb: if it takes more than 100ms, consider making it async.&lt;/p&gt;
&lt;p&gt;Moving this work to a message queue gives your users immediate feedback (&quot;we&apos;re processing your file!&quot;) while the heavy lifting happens safely in the background.&lt;/p&gt;

  &lt;div&gt;Upload, extract, chunk, embed and save in one request. A timeout or API blip throws away all the work, and other users wait.&lt;/div&gt;
  &lt;div&gt;Upload, save to S3, push a small message and return right away. Workers handle each stage, retry failures and report progress.&lt;/div&gt;

&lt;h2&gt;The anatomy of a document pipeline&lt;/h2&gt;
&lt;p&gt;A solid RAG pipeline is a series of decoupled stages, not one big function. I break it into modular steps, each triggered by a message in a queue, so you can scale each part on its own.&lt;/p&gt;
&lt;h3&gt;Four stages&lt;/h3&gt;
&lt;p&gt;Here is how I usually structure it:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Ingestion and discovery:&lt;/strong&gt; a user uploads a file. You save it to S3 and push a small message to the queue with the &lt;code&gt;file_path&lt;/code&gt; and &lt;code&gt;tenant_id&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Parsing and normalization:&lt;/strong&gt; a worker picks up the message, downloads the file and runs it through a parser like pdfplumber or an OCR service. It sends the raw text to the next queue.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Chunking:&lt;/strong&gt; this worker splits the text into semantic sections. Keeping it in its own stage means you can swap chunking strategies (for example recursive character vs semantic) without re-running the heavy parsing step.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Embedding and indexing:&lt;/strong&gt; the final stage batches the chunks, calls your embedding API (like OpenAI or a local model) and pushes the vectors into your vector DB.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Backpressure for free&lt;/h3&gt;
&lt;p&gt;This stage-based approach is what I discuss in my post on &lt;a href=&quot;https://ansezz.com/blog/7-rag-mistakes-production/&quot;&gt;7 RAG mistakes to avoid in production&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;It gives you backpressure control. If your vector DB slows down, the &quot;index&quot; queue grows, but the &quot;parsing&quot; workers keep going.&lt;/p&gt;
&lt;p&gt;When one stage slows down, its queue grows. Every other stage keeps working.&lt;/p&gt;
&lt;figure&gt;

Draw your current document flow as boxes. Every arrow between two slow steps is a place to put a queue.

&lt;h2&gt;Retries and dead letters&lt;/h2&gt;
&lt;p&gt;In the real world, things break. APIs time out. PDFs are malformed. Workers crash.&lt;/p&gt;
&lt;h3&gt;Opt in to retries&lt;/h3&gt;
&lt;p&gt;A message queue like Redis (with BullMQ or Laravel Queues) or SQS gives you retries with almost no code, but you do have to opt in:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;BullMQ&lt;/strong&gt; defaults to a single attempt, so set &lt;code&gt;attempts&lt;/code&gt; and a &lt;code&gt;backoff&lt;/code&gt; strategy explicitly.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Laravel queues&lt;/strong&gt; take &lt;code&gt;--tries&lt;/code&gt; and &lt;code&gt;backoff&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;SQS&lt;/strong&gt; retries up to &lt;code&gt;maxReceiveCount&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When a worker fails, the message goes back onto the queue to be tried again after a delay. Use exponential backoff instead of hammering a failing API every 5 seconds: wait 10, then 60, then 300.&lt;/p&gt;
&lt;h3&gt;Quarantine what can&apos;t succeed&lt;/h3&gt;
&lt;p&gt;Some documents simply &lt;em&gt;cannot&lt;/em&gt; be processed. Maybe it&apos;s a password-protected PDF or a corrupted file, and you don&apos;t want it retrying forever and clogging your workers.&lt;/p&gt;
&lt;p&gt;This is where a &lt;strong&gt;dead-letter queue (DLQ)&lt;/strong&gt; comes in. After a set number of failed attempts, the message moves to the DLQ, a &quot;quarantine&quot; zone.&lt;/p&gt;
&lt;p&gt;SQS gives you this natively through the queue&apos;s redrive policy. With BullMQ or Laravel, you route exhausted jobs there yourself (listen for the &lt;code&gt;failed&lt;/code&gt; event in BullMQ, or use &lt;code&gt;failed_jobs&lt;/code&gt; plus a handler in Laravel). You can then inspect the failed jobs, fix the issue and re-queue them. My &lt;a href=&quot;https://ansezz.com/tools/php-unserialize/&quot;&gt;PHP unserialize tool&lt;/a&gt; decodes a &lt;code&gt;failed_jobs&lt;/code&gt; payload so you can see exactly what the job received.&lt;/p&gt;

Set explicit attempts and an exponential backoff on your embedding job today, and add a failed-job handler that records the `doc_id` and error so you can replay it.

&lt;h2&gt;Batching for efficiency&lt;/h2&gt;
&lt;p&gt;If you process 10,000 chunks, you don&apos;t want 10,000 separate API calls to your embedding provider. That is slow and expensive.&lt;/p&gt;
&lt;p&gt;Most embedding APIs and vector databases work much better with batches. A good worker pulls several messages from the queue (or gathers them in memory) and sends them as one bulk request.&lt;/p&gt;
&lt;h3&gt;Show progress&lt;/h3&gt;
&lt;p&gt;In Laravel, I often use job batching to track the progress of a large document. I can see exactly when 95% of a PDF is processed and update a progress bar for the user.&lt;/p&gt;
&lt;p&gt;For how this fits a larger architecture, see my thoughts on &lt;a href=&quot;https://ansezz.com/blog/event-driven-pubsub/&quot;&gt;event-driven pub/sub systems&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Event-driven prefetching&lt;/h2&gt;
&lt;p&gt;Queues help beyond ingestion. You can also use them for &lt;strong&gt;prefetching&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;If a user is chatting with an AI agent and the conversation is heading toward a topic, you can fire a background job to fetch related documents and warm the cache before they ask the next question. The AI feels very fast because the context is already &quot;ready&quot; when retrieval runs.&lt;/p&gt;
&lt;h3&gt;Keep the chat app simple&lt;/h3&gt;
&lt;p&gt;An event bus decouples the chat interface from these optimization tasks. The chat app just emits a &lt;code&gt;user_asked_question&lt;/code&gt; event, and a background worker decides whether to prefetch more data or update the semantic cache.&lt;/p&gt;
&lt;h2&gt;Monitoring your message queue&lt;/h2&gt;
&lt;p&gt;Once you move to a queue-based system, request latency stops being the only number that matters. You need to watch your &lt;strong&gt;queue depth&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;If the queue grows faster than your workers can clear it, you have a bottleneck.&lt;/p&gt;
&lt;h3&gt;Add workers when it grows&lt;/h3&gt;
&lt;p&gt;Tools like Docker and Coolify make this easy. I can spin up five more worker containers to handle a sudden surge in uploads.&lt;/p&gt;
&lt;p&gt;You can read more about how I manage this infra in my &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;Coolify and Docker guide&lt;/a&gt;.&lt;/p&gt;
&lt;figure&gt;

Graph queue depth per stage next to worker count. If depth keeps rising while CPU stays low, scale on depth instead of CPU.


- **Never store large files in the queue.** Pass references (like an S3 key) and keep messages small.
- **Make tasks idempotent.** Assume a message might be processed twice, and use `upsert` instead of `insert` in your vector DB.
- **Use structured logging.** Every worker log should include the `doc_id` and `tenant_id`, or &quot;why did this file fail?&quot; has no answer.
- **Scale on queue depth.** Add workers based on how many messages are waiting, not CPU alone.
- **Separate worker pools.** Keep &quot;fast&quot; tasks (like metadata updates) apart from &quot;slow&quot; ones (like OCR and embedding), so a huge PDF never blocks a simple name change.

&lt;p&gt;A document pipeline is about respecting the time it takes to process data. If big uploads are timing out your RAG app, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams build queue-based ingestion pipelines with retries and autoscaling&lt;/a&gt;, or drop a note via &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;contact&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;How are you handling long-running AI tasks today: still fighting request timeouts, or already using a queue?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>messaging</category><category>ai</category><category>rag</category><category>redis</category><category>laravel</category><category>infrastructure</category></item><item><title>Rate limiting: protecting your AI wallet</title><link>https://ansezz.com/blog/rate-limiting-ai-wallet/</link><guid isPermaLink="true">https://ansezz.com/blog/rate-limiting-ai-wallet/</guid><description>One runaway agent loop can mean a $5,000 LLM bill. Why request-per-second limits lie, and how hierarchical token-bucket limits protect your margins.</description><pubDate>Thu, 21 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;One runaway agent loop is all it takes to wake up to a $5,000 LLM bill. In AI apps, rate limits protect your margins as much as your servers.&lt;/p&gt;

- Requests per second hide cost: one request can be 50 tokens, the next 128,000. Limit tokens, not pings.
- Use three layers of token buckets in Redis: a global provider cap, a per-tenant budget tied to the plan, and a per-user share inside each tenant.
- Degrade gracefully when a budget runs out, and keep your own caps even with provider hard limits, because a provider cap stops every tenant at once.

&lt;p&gt;If you&apos;re building AI-powered SaaS or RAG systems, the main threat is often a &quot;denial of wallet&quot; attack rather than a server crash.&lt;/p&gt;
&lt;p&gt;A buggy client, a malicious user or your own experimental agent can spam your endpoints and burn through tokens and credits in minutes.&lt;/p&gt;
&lt;h3&gt;Tokens, not requests&lt;/h3&gt;
&lt;p&gt;Traditional web apps watch requests per second to keep the CPU from melting. With LLMs, you watch tokens per minute to keep the bank account from draining. For a quick feel of how text turns into tokens, try my &lt;a href=&quot;https://ansezz.com/tools/token-counter/&quot;&gt;token counter&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;You need limits that understand cost, context and the &quot;noisy neighbor&quot; problem before a single prompt reaches your vector DB.&lt;/p&gt;
&lt;h2&gt;Why requests per second lie&lt;/h2&gt;
&lt;p&gt;In a standard Laravel or Node app, a request is a request. Some take longer, but they use roughly similar resources.&lt;/p&gt;
&lt;p&gt;In AI engineering, one request might be a 50-token greeting and the next a 128,000-token context dump for a RAG pipeline.&lt;/p&gt;
&lt;h3&gt;The noisy neighbor bill&lt;/h3&gt;
&lt;p&gt;If you only limit requests, a user can stay inside &quot;10 requests per minute&quot; and still cost you 100x more than an average user. That&apos;s where the &lt;a href=&quot;https://ansezz.com/blog/laravel-multi-tenancy/&quot;&gt;noisy neighbor problem&lt;/a&gt; turns into a financial one.&lt;/p&gt;
&lt;p&gt;To protect margins, move from counting pings to counting cost.&lt;/p&gt;
&lt;h2&gt;Anatomy of a denial of wallet attack&lt;/h2&gt;
&lt;p&gt;A denial of wallet (DoW) attack is the AI version of a DDoS. The goal is to exhaust your quotas or budget until the service stops, or until you pay a huge bill.&lt;/p&gt;
&lt;h3&gt;Three ways it happens&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;The agent loop:&lt;/strong&gt; an autonomous agent gets stuck and calls your tools over and over with no &quot;max steps&quot; ceiling.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The scrapers:&lt;/strong&gt; bots try to pull your whole knowledge base by querying every permutation of your RAG system.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;The dev mistake:&lt;/strong&gt; someone wires an LLM-powered autocomplete to a search bar that fires on every keystroke.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Without token-aware limits, the provider eventually answers with &lt;code&gt;429&lt;/code&gt; rate-limit errors. By then the money is already spent.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Hierarchical rate limiting&lt;/h2&gt;
&lt;p&gt;I use three layers of limits at the &lt;a href=&quot;https://ansezz.com/blog/api-gateway-ai-stack/&quot;&gt;API gateway&lt;/a&gt;. Even if one tenant goes rogue, the rest of the platform stays healthy.&lt;/p&gt;
&lt;h3&gt;1. The global provider layer&lt;/h3&gt;
&lt;p&gt;This is the last line of defense. If your provider quota is 500,000 tokens per minute (TPM), set your internal global limit to 450,000.&lt;/p&gt;
&lt;p&gt;The buffer lets you degrade on your own terms instead of hitting a wall of provider &lt;code&gt;429&lt;/code&gt;s, which means failed user requests and retry timing you don&apos;t control.&lt;/p&gt;
&lt;h3&gt;2. The tenant layer&lt;/h3&gt;
&lt;p&gt;Every customer gets its own bucket, usually tied to the subscription tier. A &quot;Pro&quot; tenant might get 50,000 TPM while a &quot;Free&quot; one is capped at 2,000. No single company can eat your whole global quota.&lt;/p&gt;
&lt;h3&gt;3. The user or session layer&lt;/h3&gt;
&lt;p&gt;Inside a tenant you still need limits, so one employee can&apos;t use the whole organization&apos;s allocation. I set these at about 20% of the tenant&apos;s capacity.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Layer&lt;/th&gt;
&lt;th&gt;Protects against&lt;/th&gt;
&lt;th&gt;Example limit&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Global&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Hitting the provider&apos;s own limits&lt;/td&gt;
&lt;td&gt;90% of provider TPM&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Tenant&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;One customer draining the platform&lt;/td&gt;
&lt;td&gt;Pro 50,000 / Free 2,000 TPM&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;User&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;One person draining their company&lt;/td&gt;
&lt;td&gt;About 20% of tenant budget&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Count what a request costs, not how many requests arrive.&lt;/p&gt;
&lt;h2&gt;The token bucket algorithm&lt;/h2&gt;
&lt;p&gt;For most builds I use a &lt;strong&gt;token bucket&lt;/strong&gt; backed by Redis. It refills at a steady rate and lets a request through only if enough tokens are available, which absorbs short bursts while capping the sustained rate. For how it differs from a leaky bucket, see &lt;a href=&quot;https://ansezz.com/blog/rate-limiting-vs-throttling/&quot;&gt;rate limiting vs throttling&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Each tenant or user has a bucket. For every prompt, you estimate the total cost (input tokens plus the requested &lt;code&gt;max_tokens&lt;/code&gt;). If the bucket has enough, the request proceeds and the tokens are deducted.&lt;/p&gt;
&lt;h3&gt;In Laravel middleware&lt;/h3&gt;
&lt;p&gt;On a Laravel stack, you can do this in middleware with Redis, where atomic operations keep per-tenant counters cheap and race-free.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// A simplified token-bucket check in Laravel middleware
public function handle($request, Closure $next)
{
    $tenantId = $request-&amp;gt;user()-&amp;gt;tenant_id;
    $estimatedTokens = $this-&amp;gt;tokenizer-&amp;gt;estimate($request-&amp;gt;input(&apos;prompt&apos;));

    if (!$this-&amp;gt;limiter-&amp;gt;consume(&quot;tenant:{$tenantId}:tokens&quot;, $estimatedTokens)) {
        return response()-&amp;gt;json([&apos;error&apos; =&amp;gt; &apos;token budget exceeded&apos;], 429);
    }

    return $next($request);
}
&lt;/code&gt;&lt;/pre&gt;

Pull last week&apos;s LLM usage and group it by tenant and by user. If the top 1% of users account for more than a third of your tokens, add the tenant and user layers before your next launch.

&lt;h2&gt;Adaptive throttling&lt;/h2&gt;
&lt;p&gt;What happens when a user hits the limit? The default is a &lt;code&gt;429&lt;/code&gt;. I prefer graceful degradation, which I call &lt;strong&gt;adaptive throttling&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;Softer than a hard no&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Degrade the model:&lt;/strong&gt; route the request to a smaller, cheaper model in the same family.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Trim the context:&lt;/strong&gt; drop some of the retrieved RAG documents to cut input tokens.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Queue the request:&lt;/strong&gt; for non-interactive work like background summarization, push it to a message queue and process it when the bucket refills.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The user experience stays intact while your margins stay protected.&lt;/p&gt;

  &lt;div&gt;The tenant hits the budget and every request returns `429` until the bucket refills. Users see errors in the middle of their work.&lt;/div&gt;
  &lt;div&gt;Interactive requests switch to a cheaper model with less context, and background jobs wait in a queue. Users get slower or shorter answers, not failures.&lt;/div&gt;

&lt;h2&gt;Limiting the hidden RAG calls&lt;/h2&gt;
&lt;p&gt;In a RAG system, one user query often triggers several backend actions:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;One embedding call for the query.&lt;/li&gt;
&lt;li&gt;One search against the vector database.&lt;/li&gt;
&lt;li&gt;One or more LLM calls for the final answer.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;If you only limit the final LLM call, search queries can still hammer your vector database. Treat the whole RAG flow as one unit of work with its own combined budget.&lt;/p&gt;
&lt;p&gt;There are plenty of &lt;a href=&quot;https://ansezz.com/blog/7-rag-mistakes-production/&quot;&gt;common RAG production mistakes&lt;/a&gt;, and limiting only the LLM call is one of the most overlooked.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Steps to take this week&lt;/h2&gt;
&lt;h3&gt;1. Set provider spend controls, then cap in your app&lt;/h3&gt;
&lt;p&gt;Both major providers now offer hard spend limits. OpenAI&apos;s organization and project hard limits return a &lt;code&gt;429&lt;/code&gt; (&lt;code&gt;organization_spend_limit_exceeded&lt;/code&gt; or &lt;code&gt;project_spend_limit_exceeded&lt;/code&gt;) once tracked spend reaches the amount. Enforcement isn&apos;t instantaneous, so spend can slightly overshoot, and plain spend alerts only notify.&lt;/p&gt;
&lt;p&gt;On Anthropic, a spend limit you set in the Console makes requests fail with a &lt;code&gt;400&lt;/code&gt; until you raise it or the period resets.&lt;/p&gt;
&lt;p&gt;Turn them on as a backstop. A provider cap stops every tenant at once, so the per-tenant caps still belong in your app.&lt;/p&gt;
&lt;h3&gt;2. Enforce &lt;code&gt;max_tokens&lt;/code&gt;&lt;/h3&gt;
&lt;p&gt;Never allow an uncapped response. Set a sane default for &lt;code&gt;max_tokens&lt;/code&gt; on every API call.&lt;/p&gt;
&lt;h3&gt;3. Set a per-request timeout&lt;/h3&gt;
&lt;p&gt;If an LLM call runs longer than 30 seconds, kill it. Slow calls are often the first sign of a system about to spiral.&lt;/p&gt;

Open your provider console today and set a hard spend limit at about twice your normal monthly spend, plus alerts at 50% and 80%. Then write down what your app should do when that limit returns errors.


- **Limit tokens, not requests.** Request counts hide the 100x cost spread between prompts.
- **Layer your buckets.** Global, tenant and user limits keep one bad actor from hurting everyone.
- **Degrade before you deny.** Cheaper models, trimmed context and queues beat a wall of `429`s.
- **Budget the whole RAG flow.** Embeddings and vector searches cost money too.
- **Use provider hard limits as a backstop.** Your own caps do the fine-grained work.

&lt;p&gt;Rate limiting is part of your business model in the AI era. You can&apos;t scale a product that lets one user run up a thousand-dollar bill in the first hour. If you&apos;re adding AI to a multi-tenant product, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams build token budgets and gateway limits&lt;/a&gt;, or &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;drop me a note&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Have you seen a &quot;denial of wallet&quot; happen in the wild, or are you still relying on provider limits alone?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>laravel</category><category>security</category><category>multi-tenancy</category><category>redis</category><category>api-design</category><category>llm</category><category>rag</category></item><item><title>API gateway: the front door of your AI stack</title><link>https://ansezz.com/blog/api-gateway-ai-stack/</link><guid isPermaLink="true">https://ansezz.com/blog/api-gateway-ai-stack/</guid><description>Stop exposing LLM providers to your frontend. The API gateway pattern for AI apps: tenant isolation, model aliases, rate limiting, and streaming-safe timeouts.</description><pubDate>Wed, 20 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Stop exposing your models to the wild. Put a gateway between your users and every LLM call.&lt;/p&gt;

- Calling a RAG orchestrator or an LLM provider straight from the frontend is slow, insecure and the fastest route to a surprise five-figure bill.
- An API gateway centralizes auth, tenant isolation, model routing and per-user rate limits before any token is spent.
- AI traffic needs two special settings: no response buffering for streaming, and upstream timeouts long enough for slow generations.

&lt;p&gt;If you are building a production AI app, sending requests directly from your frontend to a RAG orchestrator (or, god forbid, straight to an LLM provider) is a liability.&lt;/p&gt;
&lt;p&gt;It is slow. It is insecure. And it is the fastest way to wake up to a five-figure bill you didn&apos;t plan for.&lt;/p&gt;
&lt;p&gt;I have spent over a decade building software. Engineering for &quot;it works&quot; is not the same as engineering for &quot;it scales.&quot;&lt;/p&gt;
&lt;p&gt;In AI, scale means cost, latency and data safety as much as traffic.&lt;/p&gt;
&lt;h2&gt;What can go wrong without a gateway&lt;/h2&gt;
&lt;p&gt;Imagine a &quot;denial of wallet&quot; attack where a malicious script spams your completions endpoint. Without a gatekeeper, your API keys are sitting ducks.&lt;/p&gt;
&lt;p&gt;Or worse, imagine a multi-tenant app where one user&apos;s prompt accidentally retrieves another user&apos;s private data from your vector DB.&lt;/p&gt;
&lt;p&gt;This is where the API gateway comes in. It is the first line of defense and the brain of your infrastructure. It handles the boring but critical work so your RAG logic can stay focused on being smart.&lt;/p&gt;
&lt;h2&gt;The gatekeeper pattern&lt;/h2&gt;
&lt;p&gt;At its core, an API gateway is a reverse proxy that sits between your users and your backend services.&lt;/p&gt;
&lt;p&gt;For an AI stack, forwarding traffic is the smallest part of its job. It is the central point for auth, routing and rate limiting. (If the distinction blurs for you, I break it down in &lt;a href=&quot;https://ansezz.com/blog/load-balancer-vs-api-gateway/&quot;&gt;load balancer vs API gateway&lt;/a&gt;.)&lt;/p&gt;
&lt;p&gt;When a request hits your gateway, it runs a gauntlet of checks before it ever touches a model. This &quot;gatekeeper&quot; makes sure every millisecond of GPU time and every cent of token cost is intentional.&lt;/p&gt;
&lt;p&gt;Every token you pay for should pass a checkpoint first.&lt;/p&gt;
&lt;h2&gt;Authentication and tenant isolation&lt;/h2&gt;
&lt;p&gt;In a typical SaaS, authentication is about knowing who the user is. In an AI-powered SaaS, it is about data sovereignty.&lt;/p&gt;
&lt;p&gt;If you are building a RAG system, your biggest risk is cross-tenant data leakage. To avoid &lt;a href=&quot;https://ansezz.com/blog/7-rag-mistakes-production/&quot;&gt;common RAG mistakes&lt;/a&gt;, handle identity at the very edge.&lt;/p&gt;
&lt;h3&gt;JWT claims to tenant header&lt;/h3&gt;
&lt;p&gt;I prefer JWTs (JSON Web Tokens) with custom claims. When a request hits the gateway, I validate the token and extract the &lt;code&gt;tenant_id&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;That ID is injected into the request headers before it is passed to the RAG orchestrator.&lt;/p&gt;
&lt;h3&gt;The orchestrator never guesses&lt;/h3&gt;
&lt;p&gt;The orchestrator receives a verified &lt;code&gt;x-tenant-id&lt;/code&gt; header and uses it to apply metadata filters on the vector database. The user only &quot;sees&quot; data they are allowed to see.&lt;/p&gt;
&lt;p&gt;No tenant ID? No query. Period.&lt;/p&gt;

Send a request to your RAG endpoint with no tenant header and one with a forged tenant ID. Both should be rejected at the gateway before the orchestrator logs anything.

&lt;figure&gt;
&lt;h2&gt;Smart routing for model flexibility&lt;/h2&gt;
&lt;p&gt;The AI world moves fast. Today you are using GPT-6 Astra. Tomorrow, Claude Opus 5.5 might be the better play.&lt;/p&gt;
&lt;p&gt;Next week, you might want to test a fine-tuned open-weights model, like Meta&apos;s Muse Glimmer, running on your own infrastructure via &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;Docker and Coolify&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If your model logic is hardcoded into your frontend or a single monolithic backend, switching models is a nightmare. An API gateway solves this with smart routing.&lt;/p&gt;
&lt;h3&gt;Model aliases&lt;/h3&gt;
&lt;p&gt;I use the gateway to create &quot;model aliases.&quot; Instead of calling a specific model, the frontend calls a generic endpoint like &lt;code&gt;/chat/pro&lt;/code&gt;. The gateway then decides where to send the request based on:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;User tier.&lt;/strong&gt; Free users get routed to a cheaper, faster model like GPT-6 Luna or Claude Haiku. Pro users get the heavy hitters.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Versioning.&lt;/strong&gt; Run an A/B test by routing 10% of traffic to a new model version without changing a single line of client-side code.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Failover.&lt;/strong&gt; If OpenAI is having an outage, the gateway can reroute traffic to an Anthropic backup.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This level of abstraction is what separates a weekend project from a resilient SaaS product.&lt;/p&gt;

  &lt;div&gt;The frontend calls one provider&apos;s model by name. A model swap, an A/B test or an outage means a client release.&lt;/div&gt;
  &lt;div&gt;The frontend calls `/chat/pro`. The gateway picks the model by tier, test bucket or provider health, and you change it in config.&lt;/div&gt;

&lt;h2&gt;Rate limiting: protecting the wallet&lt;/h2&gt;
&lt;p&gt;We used to rate limit to protect our CPUs. Now we rate limit to protect our bank accounts.&lt;/p&gt;
&lt;p&gt;AI requests are asymmetric. A user sends a 50-word prompt, and the model might generate a 1,000-word response. The cost difference is massive.&lt;/p&gt;
&lt;h3&gt;Global and per-tenant limits&lt;/h3&gt;
&lt;p&gt;A good gateway setup allows tiered rate limiting. Set global limits so the whole system can&apos;t be overwhelmed, and set per-tenant or per-user limits too.&lt;/p&gt;
&lt;p&gt;I usually implement this with Redis. The gateway checks the user&apos;s quota in real time.&lt;/p&gt;
&lt;p&gt;If they have exceeded their daily token limit or their requests-per-minute (RPM) cap, the gateway returns &lt;code&gt;429 Too Many Requests&lt;/code&gt; immediately. I go deeper on the token-budget angle in &lt;a href=&quot;https://ansezz.com/blog/rate-limiting-ai-wallet/&quot;&gt;rate limiting to protect your AI wallet&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Why it pays off&lt;/h3&gt;
&lt;p&gt;This saves your backend from doing expensive work you won&apos;t get paid for.&lt;/p&gt;
&lt;p&gt;It also stops &quot;noisy neighbors&quot;: one user scripting an automated tool that hogs your capacity and makes the app slow for everyone else.&lt;/p&gt;

Pick your most expensive AI route and set two limits on it today: a per-user daily token cap and a global requests-per-minute ceiling. Return a clear 429 message so the frontend can explain it.

&lt;h2&gt;Handling the AI-specific quirks&lt;/h2&gt;
&lt;p&gt;Gateways for AI need to handle two things differently than traditional web apps: streaming and long-running requests.&lt;/p&gt;
&lt;h3&gt;Streaming support&lt;/h3&gt;
&lt;p&gt;Most modern AI apps use Server-Sent Events (SSE) to stream responses word by word. Some older gateways or load balancers &quot;buffer&quot; the entire response before sending it to the client. This kills the user experience.&lt;/p&gt;
&lt;p&gt;Make sure your gateway (whether you use &lt;a href=&quot;https://konghq.com/&quot;&gt;Kong&lt;/a&gt;, &lt;a href=&quot;https://tyk.io/&quot;&gt;Tyk&lt;/a&gt; or a custom &lt;a href=&quot;https://ansezz.com/blog/laravel-multi-tenancy/&quot;&gt;Laravel solution&lt;/a&gt;) disables buffering for AI routes.&lt;/p&gt;
&lt;p&gt;The data should flow through the gateway like water through a pipe, not like a bucket that needs to fill first.&lt;/p&gt;
&lt;h3&gt;Extended timeouts&lt;/h3&gt;
&lt;p&gt;Traditional APIs expect a response in 1 to 2 seconds. A complex RAG query with multiple vector searches and a large model generation might take 30 seconds or more.&lt;/p&gt;
&lt;p&gt;You need to adjust your gateway&apos;s &quot;upstream timeout&quot; settings:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Gateway&lt;/th&gt;
&lt;th&gt;Default upstream timeout&lt;/th&gt;
&lt;th&gt;Can you raise it?&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Kong&lt;/td&gt;
&lt;td&gt;60 seconds&lt;/td&gt;
&lt;td&gt;Yes, per service&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;AWS API Gateway (REST)&lt;/td&gt;
&lt;td&gt;29 seconds&lt;/td&gt;
&lt;td&gt;Only on Regional or private REST APIs, via a service quota increase that may cost throttle headroom&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Leave those defaults in place and your users will see &lt;code&gt;504 Gateway Timeout&lt;/code&gt; errors even when your models are working perfectly.&lt;/p&gt;

Time your slowest real RAG query end to end, add a safety margin, and set that as the upstream timeout on your AI routes only. Keep the short default everywhere else.

&lt;figure&gt;
&lt;h2&gt;Practical steps for your stack&lt;/h2&gt;
&lt;p&gt;You don&apos;t need a massive team to set this up. Here is how I usually approach it depending on the project size.&lt;/p&gt;
&lt;h3&gt;For startups&lt;/h3&gt;
&lt;p&gt;Use a cloud-native gateway like AWS API Gateway or Azure API Management. They are serverless, scale automatically and integrate directly with Cognito or Entra ID for auth.&lt;/p&gt;
&lt;h3&gt;For self-hosters&lt;/h3&gt;
&lt;p&gt;Kong is the gold standard, with a great ecosystem of plugins for rate limiting and auth. If you are comfortable with PHP, a thin Laravel app acting as a gateway works surprisingly well for custom logic.&lt;/p&gt;
&lt;h3&gt;For Shopify devs&lt;/h3&gt;
&lt;p&gt;If you are building &lt;a href=&quot;https://ansezz.com/blog/agentic-commerce-shopify/&quot;&gt;agentic commerce tools&lt;/a&gt;, use the gateway to handle Shopify HMAC validation before passing the request to your AI agents. When a signature fails, my &lt;a href=&quot;https://ansezz.com/tools/shopify-hmac-verifier/&quot;&gt;Shopify webhook HMAC verifier&lt;/a&gt; helps you find the cause.&lt;/p&gt;
&lt;h2&gt;Why the gateway is a design choice&lt;/h2&gt;
&lt;p&gt;The API gateway is infrastructure, but it is also a statement: your AI logic is too valuable (and too expensive) to leave unprotected.&lt;/p&gt;
&lt;p&gt;By centralizing auth, routing and rate limiting, you make your system more modular. You can swap models, change pricing tiers and update security policies without touching the core code that makes your AI &quot;smart.&quot;&lt;/p&gt;

- **Centralize auth.** Never let your RAG orchestrator handle raw user authentication. Do it at the gateway.
- **Inject tenant context.** Verify the user at the gateway and inject a `tenant_id` header to enforce data isolation.
- **Set global and per-user limits.** Protect your wallet from both malicious attacks and accidental bugs.
- **Configure for streaming.** Make sure your gateway doesn&apos;t buffer responses, or your &quot;typing&quot; effect will break.
- **Use model aliases.** Route to `/chat/pro` instead of a specific model name to keep your stack flexible.

&lt;p&gt;If you&apos;re putting an LLM-backed product in front of real users and want auth, routing and cost limits done right, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams build the gateway layer&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Are you still letting your frontend talk directly to your LLM providers? If so, what is the one thing stopping you from putting a gateway in front of it?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>api-design</category><category>ai</category><category>rag</category><category>security</category><category>multi-tenancy</category><category>messaging</category><category>infrastructure</category></item><item><title>Scaling with RabbitMQ: why message brokers matter</title><link>https://ansezz.com/blog/scaling-with-rabbitmq/</link><guid isPermaLink="true">https://ansezz.com/blog/scaling-with-rabbitmq/</guid><description>Synchronous controllers are how monoliths die. RabbitMQ exchanges and queues, a one-task-at-a-time path to async, and idempotent Laravel workers.</description><pubDate>Sat, 16 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;If your checkout request waits on a PDF, an email and three third-party APIs, more RAM won&apos;t save it. Hand that work to a message broker and answer the user right away.&lt;/p&gt;

- Synchronous controllers tie your response time to the slowest secondary task, so one slow API can turn into a 504 for the user.
- RabbitMQ sits in the middle: producers publish, exchanges route, queues hold and consumers do the work at their own pace.
- Move one slow task at a time to a queue, scale workers on their own, and make every worker idempotent.

&lt;p&gt;Every time a user hits &quot;checkout,&quot; your server generates a PDF, sends a welcome email, updates inventory and calls three third-party APIs.&lt;/p&gt;
&lt;p&gt;If any of those services takes too long to answer, the user sees a 504 gateway timeout.&lt;/p&gt;
&lt;h3&gt;The monolith wall&lt;/h3&gt;
&lt;p&gt;It starts as a small delay, then becomes a bottleneck. Soon you&apos;re adding RAM to a problem bigger hardware can&apos;t fix.&lt;/p&gt;
&lt;p&gt;When everything is synchronous, one failure in a secondary task breaks the whole user experience. I&apos;ve watched dashboards turn red during a marketing spike because the database was busy with background reports and couldn&apos;t handle new signups.&lt;/p&gt;
&lt;h3&gt;Change how services talk&lt;/h3&gt;
&lt;p&gt;The fix is to change how your services talk to each other: &lt;strong&gt;decoupling&lt;/strong&gt;, with a broker like &lt;strong&gt;RabbitMQ&lt;/strong&gt;.&lt;/p&gt;
&lt;h2&gt;Why your request path is too crowded&lt;/h2&gt;
&lt;p&gt;In a typical web app we do too much inside the controller. A request arrives and we finish every related task before sending back &quot;200 OK.&quot; That&apos;s fine with ten users. For a growing SaaS, it breaks.&lt;/p&gt;
&lt;h3&gt;The coffee shop&lt;/h3&gt;
&lt;p&gt;Picture a coffee shop where the person taking your order also grinds the beans, steams the milk and draws the logo on the cup before taking the next order. The line wraps around the block, because the cashier is tightly coupled to the barista&apos;s work.&lt;/p&gt;
&lt;p&gt;To scale, the cashier writes the order on a slip and hands it off, and is free for the next customer. That slip is your message. The counter where the slips go is your message broker.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;How RabbitMQ routes work&lt;/h2&gt;
&lt;p&gt;RabbitMQ is an open-source message broker that sits between the parts of your system. It stores messages and also routes them by rules you define.&lt;/p&gt;
&lt;h3&gt;The four pieces&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Producers:&lt;/strong&gt; your web apps or APIs that create a task.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Exchanges:&lt;/strong&gt; the post office that decides which queue a message goes to, based on rules.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Queues:&lt;/strong&gt; where messages wait until they are processed.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Consumers:&lt;/strong&gt; background workers (often in Docker containers) that do the work.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;With RabbitMQ in the middle, the web tier only has to say &quot;this task needs doing.&quot; That takes milliseconds. The user gets an instant confirmation while workers handle the heavy work when they&apos;re ready.&lt;/p&gt;

  &lt;div&gt;The controller builds the PDF, sends the email, updates inventory and calls three APIs before it responds. One slow API and the user gets a 504.&lt;/div&gt;
  &lt;div&gt;The controller saves the order, publishes `order.placed` and responds. Workers build the PDF and send the email from the queue, and retry if a provider is down.&lt;/div&gt;

&lt;h2&gt;Smoothing out the spikes&lt;/h2&gt;
&lt;p&gt;Sudden bursts and noisy neighbors are among the hardest parts of scaling. If an enterprise client uploads a 100,000-row CSV, you don&apos;t want the login page to slow down for everyone else.&lt;/p&gt;
&lt;p&gt;That&apos;s exactly the work &lt;a href=&quot;https://ansezz.com/blog/message-queues-document-processing/&quot;&gt;message queues for heavy document processing&lt;/a&gt; are built to absorb.&lt;/p&gt;
&lt;h3&gt;Scale the workers, not the app&lt;/h3&gt;
&lt;p&gt;With RabbitMQ, those 100,000 rows become 100,000 messages. Workers process them at a steady pace. If the queue grows, you add worker instances instead of scaling the whole application.&lt;/p&gt;
&lt;p&gt;That&apos;s &lt;a href=&quot;https://ansezz.com/blog/horizontal-vs-vertical-scaling/&quot;&gt;horizontal scaling&lt;/a&gt; in its simplest form: workers are decoupled from the web server, so each scales on its own load.&lt;/p&gt;
&lt;h3&gt;RabbitMQ in Laravel&lt;/h3&gt;
&lt;p&gt;Laravel&apos;s queue system ships drivers for the database, Amazon SQS, Redis and Beanstalkd. To talk to RabbitMQ directly, you add the community package &lt;code&gt;vladimir-yuldashev/laravel-queue-rabbitmq&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;Your web tier should take the order. Your workers should make the coffee.&lt;/p&gt;
&lt;h2&gt;Moving from sync to async&lt;/h2&gt;
&lt;p&gt;You don&apos;t have to rewrite the codebase overnight. Pick one slow, low-risk task, like the &quot;forgot password&quot; email or an image resize, and move only that to a queue. Then pick the next one.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// instead of sending the email directly
// $emailService-&amp;gt;sendWelcome($user);

// dispatch a job to the RabbitMQ-backed queue
ProcessWelcomeEmail::dispatch($user)-&amp;gt;onQueue(&apos;high-priority&apos;);

// the user gets a response right away
return response()-&amp;gt;json([
    &apos;message&apos; =&amp;gt; &apos;welcome! check your inbox soon.&apos;,
]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now if your email provider (SendGrid, Mailgun or similar) has a bad day, your app stays up. The message waits in RabbitMQ until the service is back.&lt;/p&gt;

Time every step inside your slowest controller action. Anything the user doesn&apos;t need to see in the response, and that takes more than 100 ms, goes on your list of jobs to queue first.

&lt;h2&gt;Building for what comes next&lt;/h2&gt;
&lt;p&gt;A broker-first mindset is the first step &lt;a href=&quot;https://ansezz.com/blog/monolith-to-microservices/&quot;&gt;from a monolith to microservices&lt;/a&gt;. Once your monolith publishes events like &lt;code&gt;order.placed&lt;/code&gt; or &lt;code&gt;user.registered&lt;/code&gt;, other services can listen without you changing the original code.&lt;/p&gt;
&lt;h3&gt;See the backlog&lt;/h3&gt;
&lt;p&gt;The system also gets easier to observe and debug. The RabbitMQ management UI shows how many tasks are pending and how fast they&apos;re being processed, so you stop guessing why the server is slow.&lt;/p&gt;
&lt;p&gt;Already on GCP? The same patterns apply with &lt;a href=&quot;https://ansezz.com/blog/event-driven-pubsub/&quot;&gt;Google Pub/Sub&lt;/a&gt;. Pick the broker that matches your hosting stack, not the trend cycle.&lt;/p&gt;
&lt;figure&gt;

Pick one job and run it twice with the same payload in a test. If it sends two emails or charges twice, add an idempotency key (like the order ID) and check it before doing the work.


- **Don&apos;t block the user.** If a task takes more than 100 ms and the response doesn&apos;t need it, it probably belongs in a queue.
- **Decouple early.** Separate the &quot;thinking&quot; (web tier) from the &quot;doing&quot; (workers).
- **Make workers idempotent.** Messages can be delivered more than once, so the same task must be safe to run twice.
- **Monitor queue depth.** A growing queue is an early sign you need more workers or a downstream service is failing.

&lt;p&gt;Scaling a SaaS is about giving your work room to breathe, and a broker gives you that room. If you&apos;re pulling slow work off your request path, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams design queues and workers that scale&lt;/a&gt;, or &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;tell me about it&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;What&apos;s the slowest part of your application right now, and could it run as a background job?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>messaging</category><category>microservices</category><category>scaling</category><category>laravel</category><category>architecture</category></item><item><title>Event-driven architecture with Google Pub/Sub</title><link>https://ansezz.com/blog/event-driven-pubsub/</link><guid isPermaLink="true">https://ansezz.com/blog/event-driven-pubsub/</guid><description>Decouple your services or drown in latency. Topics, fan-out, push vs pull, dead-letter queues, and idempotent consumers in a Laravel Pub/Sub blueprint.</description><pubDate>Sat, 02 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;If one slow service can kill your whole request, your services are glued together. Events let them work apart.&lt;/p&gt;

- A Pub/Sub topic broadcasts each event once, and every subscription gets its own copy to process at its own pace.
- Choose push delivery for serverless endpoints and pull delivery when your workers need control over backpressure.
- Add a dead-letter queue, idempotent consumers and a watch on the unacked message count before you call it production-ready.

&lt;p&gt;Building a modern web application usually starts simple. You get a request and you send a response.&lt;/p&gt;
&lt;p&gt;As your business grows, that simple flow starts to feel heavy. Maybe you need to send a welcome email, update a CRM and trigger a data warehouse sync all at once.&lt;/p&gt;
&lt;h3&gt;The cost of tight coupling&lt;/h3&gt;
&lt;p&gt;If you do this synchronously, your users are stuck staring at a loading spinner. If one service fails, the whole request dies, and your system becomes a house of cards.&lt;/p&gt;
&lt;p&gt;Your application logic is tangled like old headphones in a pocket. Every new feature adds more risk and more latency. You need a way to let your services talk without being glued together.&lt;/p&gt;
&lt;h3&gt;Events break the chain&lt;/h3&gt;
&lt;p&gt;The solution is &lt;strong&gt;event-driven architecture&lt;/strong&gt; (EDA). In the Google Cloud world, the heart of that architecture is &lt;strong&gt;Google Pub/Sub&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;It is a globally distributed messaging service that decouples the services that produce events from the services that consume them. If you&apos;d rather self-host the broker, the same patterns translate directly to &lt;a href=&quot;https://ansezz.com/blog/scaling-with-rabbitmq/&quot;&gt;scaling with RabbitMQ&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Understanding topics and subscriptions&lt;/h2&gt;
&lt;p&gt;At its core, Google Pub/Sub is built on two concepts: &lt;strong&gt;topics&lt;/strong&gt; and &lt;strong&gt;subscriptions&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;I like to think of a topic as a radio station. It broadcasts information out into the void. It doesn&apos;t care who is listening or what they do with the music.&lt;/p&gt;
&lt;h3&gt;Subscriptions are the listeners&lt;/h3&gt;
&lt;p&gt;A subscription represents a stream of messages from a specific topic. The publisher only needs to know about the topic. It doesn&apos;t need to know if there are ten consumers or zero.&lt;/p&gt;
&lt;h3&gt;Sync to async&lt;/h3&gt;
&lt;p&gt;This is the heart of the &lt;a href=&quot;https://ansezz.com/blog/synchronous-vs-asynchronous-communication/&quot;&gt;shift from synchronous to asynchronous communication&lt;/a&gt;. When a user signs up on your site, you publish a &lt;code&gt;UserSignedUp&lt;/code&gt; event to a topic.&lt;/p&gt;
&lt;p&gt;Your main app is done and returns a success message to the user right away. Meanwhile, subscribers pick up that event and do their jobs in the background.&lt;/p&gt;

  &lt;div&gt;Signup calls the email API, the CRM and the warehouse sync in a row. One failure kills the request, and the user waits for all three.&lt;/div&gt;
  &lt;div&gt;Signup publishes one `UserSignedUp` event and returns. Email, CRM and sync each pick it up on their own, and a failure in one doesn&apos;t touch the others.&lt;/div&gt;

&lt;h2&gt;The fan-out pattern&lt;/h2&gt;
&lt;p&gt;Fan-out is one of the most useful patterns in Google Pub/Sub. You publish a single message to a topic, and multiple subscriptions each receive a copy.&lt;/p&gt;
&lt;p&gt;Imagine you run an e-commerce store. When an order is placed, three services need to act:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;An inventory service to update stock levels.&lt;/li&gt;
&lt;li&gt;A shipping service to generate a label.&lt;/li&gt;
&lt;li&gt;An analytics service to track revenue.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;One message, three copies&lt;/h3&gt;
&lt;p&gt;Instead of your checkout service calling three different APIs, it sends one message to an &lt;code&gt;order-events&lt;/code&gt; topic. Three separate subscriptions (inventory, shipping, analytics) each get their own copy.&lt;/p&gt;
&lt;p&gt;They process it at their own pace. If the analytics service is down for maintenance, the shipping label still gets created. The messages wait in the subscription until the service is back online.&lt;/p&gt;
&lt;p&gt;Checkout publishes once and moves on. Every downstream service works on its own clock.&lt;/p&gt;
&lt;figure&gt;

Pick one place where a request calls two or more services in a row. Replace those calls with one published event and one subscription per service.

&lt;h2&gt;Pull vs push delivery&lt;/h2&gt;
&lt;p&gt;When you set up a subscription, you decide how you want to receive messages. Google Pub/Sub gives you two main options: &lt;strong&gt;pull&lt;/strong&gt; and &lt;strong&gt;push&lt;/strong&gt;.&lt;/p&gt;
&lt;h3&gt;Push subscriptions&lt;/h3&gt;
&lt;p&gt;Push subscriptions suit serverless architectures. Google Cloud sends the message to a webhook URL you provide.&lt;/p&gt;
&lt;p&gt;This fits &lt;a href=&quot;https://ansezz.com/work/&quot;&gt;cloud infrastructure&lt;/a&gt; built on Cloud Run or Cloud Functions. It scales automatically and you only pay for what you use. You do have to make sure your endpoint can handle sudden spikes in traffic.&lt;/p&gt;
&lt;h3&gt;Pull subscriptions&lt;/h3&gt;
&lt;p&gt;With pull, your consumer service asks Google Pub/Sub for messages when it is ready. This gives you much more control over backpressure: if your worker is busy, it doesn&apos;t ask for more work.&lt;/p&gt;
&lt;p&gt;Pull is the usual choice for long-running services or for tools like Laravel&apos;s queue workers. It holds up better for heavy processing where you want to fine-tune concurrency, which is the model I use for &lt;a href=&quot;https://ansezz.com/blog/message-queues-document-processing/&quot;&gt;message queues in document processing&lt;/a&gt;.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Delivery&lt;/th&gt;
&lt;th&gt;How messages arrive&lt;/th&gt;
&lt;th&gt;Good fit&lt;/th&gt;
&lt;th&gt;Watch out for&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Push&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Pub/Sub calls your webhook URL&lt;/td&gt;
&lt;td&gt;Cloud Run, Cloud Functions, serverless&lt;/td&gt;
&lt;td&gt;Sudden traffic spikes on the URL&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Pull&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Your worker asks when it is ready&lt;/td&gt;
&lt;td&gt;Long-running workers, Laravel queue workers&lt;/td&gt;
&lt;td&gt;You manage the workers yourself&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;Building resilient systems with DLQs&lt;/h2&gt;
&lt;p&gt;In a distributed system, things will fail. A database might time out or an external API might be down. If a message can&apos;t be processed, you don&apos;t want to lose it.&lt;/p&gt;
&lt;p&gt;This is where &lt;strong&gt;dead-letter queues&lt;/strong&gt; (DLQs) come in.&lt;/p&gt;
&lt;h3&gt;Move the poison message aside&lt;/h3&gt;
&lt;p&gt;A DLQ is another topic where Google Pub/Sub sends messages that failed to be acknowledged after a set number of attempts. Instead of retrying forever and clogging your main pipeline, the &quot;poison&quot; message is moved aside.&lt;/p&gt;
&lt;h3&gt;Inspect, fix, replay&lt;/h3&gt;
&lt;p&gt;I always recommend a DLQ for every important subscription. It acts as a safety net.&lt;/p&gt;
&lt;p&gt;You can build a small dashboard or script to inspect the failed messages, fix the underlying issue and replay them. For Laravel jobs, my &lt;a href=&quot;https://ansezz.com/tools/php-unserialize/&quot;&gt;PHP unserialize tool&lt;/a&gt; turns a failed payload back into readable data. That prevents data loss and keeps your system moving.&lt;/p&gt;
&lt;figure&gt;

Attach a dead-letter topic to your busiest subscription, then write a short script that lists what lands there so you can fix and replay it.

&lt;h2&gt;Integrating Google Pub/Sub with Laravel&lt;/h2&gt;
&lt;p&gt;For the PHP and Laravel ecosystem, integrating Google Pub/Sub is smooth. Laravel ships with solid queue support for Redis and SQS, and the &lt;code&gt;google/cloud-pubsub&lt;/code&gt; client lets you tap into GCP&apos;s global scale.&lt;/p&gt;
&lt;p&gt;This kind of decoupling is what makes the &lt;a href=&quot;https://ansezz.com/blog/monolith-to-microservices/&quot;&gt;move from a monolith to microservices&lt;/a&gt; manageable instead of terrifying.&lt;/p&gt;
&lt;h3&gt;Publishing a message&lt;/h3&gt;
&lt;p&gt;You can treat Google Pub/Sub as a custom queue driver. Here is how you might publish a message in a typical service class:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;use Google\Cloud\PubSub\PubSubClient;

$pubsub = new PubSubClient([
    &apos;projectId&apos; =&amp;gt; &apos;your-gcp-project-id&apos;,
]);

$topic = $pubsub-&amp;gt;topic(&apos;user-events&apos;);

$topic-&amp;gt;publish([
    &apos;data&apos; =&amp;gt; json_encode([
        &apos;user_id&apos; =&amp;gt; 123,
        &apos;action&apos; =&amp;gt; &apos;signup&apos;,
    ]),
    &apos;attributes&apos; =&amp;gt; [
        &apos;event_type&apos; =&amp;gt; &apos;UserSignedUp&apos;,
        &apos;priority&apos; =&amp;gt; &apos;high&apos;,
    ],
]);
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Filter with attributes&lt;/h3&gt;
&lt;p&gt;Attributes let you filter messages at the subscription level. A subscriber can choose to only receive messages where &lt;code&gt;event_type&lt;/code&gt; is &lt;code&gt;UserSignedUp&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;That saves compute and outbound traffic, because your worker never sees the messages it doesn&apos;t care about.&lt;/p&gt;
&lt;h2&gt;Monitoring and cost management&lt;/h2&gt;
&lt;p&gt;Set up monitoring from day one. Google Cloud integrates Cloud Monitoring with Google Pub/Sub.&lt;/p&gt;
&lt;p&gt;Keep a close eye on your &quot;unacked message count.&quot; If this number keeps climbing, your subscribers can&apos;t keep up with the producers.&lt;/p&gt;
&lt;h3&gt;Keep the bill in check&lt;/h3&gt;
&lt;p&gt;Google Pub/Sub is cheap at low volumes, but at millions of messages those bytes add up. Use batching on the publisher side to reduce the number of API calls.&lt;/p&gt;
&lt;p&gt;Also watch message retention. The default is seven days, and you can set anywhere from 10 minutes up to 31 days. Keeping unacknowledged messages for more than 24 hours adds storage cost, so shorten the window if you don&apos;t need a long replay.&lt;/p&gt;

Set an alert on the unacked message count for each subscription, and check whether your retention period is longer than you actually need.


- **Start by finding the &quot;facts&quot;** in your system (for example `OrderPlaced`) and turn them into events.
- **Use the fan-out pattern** to keep your services decoupled and focused on one task.
- **Always add a dead-letter queue** so failures don&apos;t block the main pipeline.
- **Use message attributes for filtering** at the subscription level.
- **Make your consumers idempotent.** If they receive the same message twice, it doesn&apos;t cause errors or double charges.

&lt;p&gt;This takes more planning up front, and I use it as the backbone of many systems I build because the payoff in stability is worth it. If you want help moving a synchronous flow to events, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams design event-driven systems on Pub/Sub and Laravel&lt;/a&gt;, or &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;let me know what&apos;s stopping you&lt;/a&gt; from making the switch.&lt;/p&gt;
&lt;p&gt;Are you still using synchronous API calls for everything, or have you started moving toward an event-driven flow?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>messaging</category><category>cloud-platforms</category><category>laravel</category><category>scaling</category><category>architecture</category></item><item><title>Vibe coding: the shift to agentic workflows</title><link>https://ansezz.com/blog/agentic-workflows-vibe-coding/</link><guid isPermaLink="true">https://ansezz.com/blog/agentic-workflows-vibe-coding/</guid><description>MCP, agentic loops, and intent-based engineering. How vibe coding becomes a real architecture pattern, plus the Laravel and MCP stack I run today.</description><pubDate>Sun, 22 Mar 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Coding used to mean translating intent into syntax, line by line. Agentic workflows flip that: you state the intent, and a loop of tools does the typing.&lt;/p&gt;

- Chat-style AI assistants left you as the manual bridge between the model and your system: copy, paste, test, repeat.
- Agentic loops (intent, reasoning, action, observation, correction) let the model reach your tools directly, mostly through MCP.
- The human job becomes architecture and review: small scoped MCP servers, stateful agent tools and a sign-off gate before any action runs.

&lt;p&gt;I&apos;ve spent the last decade building Laravel applications, managing Docker clusters and fine-tuning Shopify stores.&lt;/p&gt;
&lt;p&gt;For most of that time, &quot;coding&quot; meant one thing: translating a business requirement into syntax a machine could execute. It was a manual, linear process of writing line by line, debugging stack traces and managing state.&lt;/p&gt;
&lt;p&gt;Recently, the ground has shifted. We&apos;re moving away from &quot;writing code&quot; and into &quot;orchestrating intent.&quot;&lt;/p&gt;
&lt;p&gt;This transition is often playfully called &lt;strong&gt;vibe coding&lt;/strong&gt;. The meme hides a real architectural change: a move from sequential instructions to &lt;strong&gt;agentic workflows&lt;/strong&gt; powered by protocols like &lt;strong&gt;MCP&lt;/strong&gt; (Model Context Protocol).&lt;/p&gt;
&lt;p&gt;If you are new to the idea, my &lt;a href=&quot;https://ansezz.com/blog/vibe-coding/&quot;&gt;intro to vibe coding&lt;/a&gt; covers the philosophy and developer-experience side before this post dives into the architecture.&lt;/p&gt;
&lt;h2&gt;The friction of manual syntax&lt;/h2&gt;
&lt;p&gt;The traditional development lifecycle is full of invisible friction. You have an idea (the &quot;vibe&quot;), you break it into tasks, and then you spend 80% of your time fighting syntax, configuration and boilerplate.&lt;/p&gt;
&lt;p&gt;In a standard &lt;strong&gt;Laravel&lt;/strong&gt; environment, even a simple feature like an automated reporting tool needs routes, controllers, service classes and database migrations.&lt;/p&gt;
&lt;p&gt;You are the compiler. You are the architect. You are the labor.&lt;/p&gt;
&lt;h3&gt;The &quot;how&quot; eats the &quot;what&quot;&lt;/h3&gt;
&lt;p&gt;Our cognitive load gets consumed by the &quot;how&quot; rather than the &quot;what.&quot; We get stuck on &lt;strong&gt;PHP&lt;/strong&gt; version compatibility or &lt;strong&gt;Docker&lt;/strong&gt; networking issues and lose sight of the actual user value.&lt;/p&gt;
&lt;p&gt;This manual micromanagement doesn&apos;t scale with the demands of modern business.&lt;/p&gt;
&lt;h2&gt;The &quot;black box&quot; assistant problem&lt;/h2&gt;
&lt;p&gt;When AI first arrived as basic autocomplete, it felt like a shortcut. It wasn&apos;t a solution.&lt;/p&gt;
&lt;p&gt;We ended up with what I call &quot;the Copilot paradox&quot;: the AI suggests code, but you still copy-paste it, test it, find the error and feed it back.&lt;/p&gt;
&lt;h3&gt;A broken feedback loop&lt;/h3&gt;
&lt;p&gt;The AI is a &quot;black box&quot; that doesn&apos;t know your system. It doesn&apos;t know your database schema, your &lt;strong&gt;MCP&lt;/strong&gt; servers or your deployment status on &lt;strong&gt;Coolify&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;You are still the manual bridge between the AI&apos;s logic and your local environment.&lt;/p&gt;
&lt;h3&gt;Accelerated manual labor&lt;/h3&gt;
&lt;p&gt;This creates a new kind of fatigue. Instead of writing code, you become a high-speed code reviewer, constantly switching between your editor and a chat window.&lt;/p&gt;
&lt;p&gt;That isn&apos;t &quot;vibe coding.&quot; It&apos;s accelerated manual labor.&lt;/p&gt;

For one day, count how many times you copy code out of a chat window and paste an error back in. Each round trip is a step an agent with tool access could do on its own.

&lt;h2&gt;The fix: agentic workflows and MCP&lt;/h2&gt;
&lt;p&gt;True &lt;strong&gt;vibe coding&lt;/strong&gt; shifts your role to high-level system architect.&lt;/p&gt;
&lt;p&gt;That becomes possible through &lt;strong&gt;agentic workflows&lt;/strong&gt;: systems that execute tasks in loops instead of only completing text. That jump from a static model to an autonomous actor is exactly the &lt;a href=&quot;https://ansezz.com/blog/llm-vs-ai-agent/&quot;&gt;LLM vs AI agent&lt;/a&gt; distinction.&lt;/p&gt;
&lt;h3&gt;MCP is the connector&lt;/h3&gt;
&lt;p&gt;The breakthrough here is the &lt;strong&gt;Model Context Protocol (MCP)&lt;/strong&gt;, created by Anthropic and donated in December 2025 to the Agentic AI Foundation, a Linux Foundation fund, so it is now vendor-neutral.&lt;/p&gt;
&lt;p&gt;MCP acts as the &quot;USB-C port&quot; for AI applications. Instead of you handing the AI context, the AI uses an MCP client to talk directly to your tools: your &lt;strong&gt;PostgreSQL&lt;/strong&gt; database, your &lt;strong&gt;Slack&lt;/strong&gt; channels or your &lt;strong&gt;GitHub&lt;/strong&gt; repositories.&lt;/p&gt;

  &lt;div&gt;You paste context in, copy code out, run it, paste the error back. You are the bridge between the model and your system.&lt;/div&gt;
  &lt;div&gt;The agent reads the schema, runs the migration, reads the error and fixes it through MCP tools. You approve the plan.&lt;/div&gt;

&lt;figure&gt;
&lt;h2&gt;From chains to loops&lt;/h2&gt;
&lt;p&gt;In a traditional chain, you give a prompt and get a result. In an agentic loop, the architecture looks like this:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Intent.&lt;/strong&gt; You describe the outcome (&quot;build a Laravel dashboard for my Shopify sales&quot;).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Reasoning.&lt;/strong&gt; The AI (like &lt;strong&gt;Claude&lt;/strong&gt;) works out that it needs to see the schema.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Action.&lt;/strong&gt; It uses an &lt;strong&gt;MCP&lt;/strong&gt; tool to query the database.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Observation.&lt;/strong&gt; It sees a missing table and decides to create a migration.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Correction.&lt;/strong&gt; If the migration fails, it reads the error and fixes it itself.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Intent-based engineering&lt;/h3&gt;
&lt;p&gt;I call this &quot;intent-based engineering.&quot; You aren&apos;t writing the migration. You are approving the architectural decision.&lt;/p&gt;
&lt;p&gt;Nobody lands here on day one. The jump from chat prompts to loops is a progression I broke into &lt;a href=&quot;https://ansezz.com/blog/ai-coding-workflow-levels/&quot;&gt;levels of an AI coding workflow&lt;/a&gt;, and MCP sits near the top of it.&lt;/p&gt;
&lt;p&gt;Stop typing the migration. Start approving the decision behind it.&lt;/p&gt;
&lt;h2&gt;Implementing the agentic stack&lt;/h2&gt;
&lt;p&gt;As an engineer who values quality, I don&apos;t let the &quot;vibe&quot; take over without guardrails.&lt;/p&gt;
&lt;p&gt;The loop only stays safe if something verifies what comes out of it. That is the whole argument in &lt;a href=&quot;https://ansezz.com/blog/testing-ai-generated-code/&quot;&gt;trust is not a QA strategy&lt;/a&gt;. Here is how I structure my agentic stack using &lt;strong&gt;Laravel&lt;/strong&gt; and &lt;strong&gt;AI&lt;/strong&gt; today.&lt;/p&gt;
&lt;h3&gt;1. Defined MCP servers&lt;/h3&gt;
&lt;p&gt;I build small, dedicated &lt;strong&gt;MCP&lt;/strong&gt; servers that expose only the tools the AI needs. This keeps the context window clean and the security tight.&lt;/p&gt;
&lt;p&gt;I go deeper on this in &lt;a href=&quot;https://ansezz.com/blog/claude-mcp-dev-tools/&quot;&gt;Claude MCP dev tools&lt;/a&gt; and on designing &lt;a href=&quot;https://ansezz.com/blog/mcp-context-aware-agents/&quot;&gt;context-aware agents with MCP&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// Conceptual MCP tool definition in a PHP environment
public function defineTools(): array
{
    return [
        &apos;get_database_schema&apos; =&amp;gt; [
            &apos;description&apos; =&amp;gt; &apos;Retrieves the structure of the Laravel application tables.&apos;,
            &apos;parameters&apos; =&amp;gt; [],
        ],
        &apos;run_artisan_command&apos; =&amp;gt; [
            &apos;description&apos; =&amp;gt; &apos;Executes an artisan command safely.&apos;,
            &apos;parameters&apos; =&amp;gt; [&apos;command&apos; =&amp;gt; &apos;string&apos;],
        ],
    ];
}
&lt;/code&gt;&lt;/pre&gt;

Write down the three tools your agent actually needs for one task (for example: read schema, run tests, run one artisan command). Expose only those in your MCP server and leave everything else out.

&lt;h3&gt;2. Stateful loops&lt;/h3&gt;
&lt;p&gt;Instead of one-off chats, I use tools like &lt;strong&gt;Cursor&lt;/strong&gt;, &lt;strong&gt;Claude Code&lt;/strong&gt; or &lt;strong&gt;Devin Desktop&lt;/strong&gt; (the IDE formerly called &lt;strong&gt;Windsurf&lt;/strong&gt;) that keep a stateful connection to my local file system.&lt;/p&gt;
&lt;p&gt;The agent can &quot;see&quot; the impact of its changes in real time, just like a human developer would.&lt;/p&gt;
&lt;h3&gt;3. The human-in-the-loop (HITL)&lt;/h3&gt;
&lt;p&gt;The most important part of the architecture is the review gate. Even with agentic loops, the human architect must sign off on the &quot;plan&quot; before the &quot;action&quot; phase.&lt;/p&gt;
&lt;p&gt;This keeps the &lt;strong&gt;PHP&lt;/strong&gt; logic on clean architecture principles rather than just &quot;making it work.&quot;&lt;/p&gt;
&lt;p&gt;What that gate should actually check is a separate question. I argue for &lt;a href=&quot;https://ansezz.com/blog/stop-reading-code-ai-review/&quot;&gt;dropping line-by-line reading&lt;/a&gt; in favor of specs and automated verification, and I cover approval gates for writes in &lt;a href=&quot;https://ansezz.com/blog/hitl-gates-for-agent-mutations/&quot;&gt;HITL gates for agent mutations&lt;/a&gt;.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;What this means for founders&lt;/h2&gt;
&lt;p&gt;If you&apos;re a founder or a CTO, the lesson is simple: stop hiring for syntax and start hiring for system design. The technical barrier is collapsing, but the architectural stakes are higher than ever.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Embrace the vibe.&lt;/strong&gt; Focus on the intent and the user experience.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Invest in infrastructure.&lt;/strong&gt; Build the &lt;strong&gt;MCP&lt;/strong&gt; connections and data pipelines that let AI be effective.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Think in loops.&lt;/strong&gt; Design internal processes so AI can iterate on its own, which removes you as the bottleneck.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I now build agent-ready systems, whether it&apos;s a complex &lt;strong&gt;Shopify&lt;/strong&gt; integration or a custom &lt;strong&gt;SaaS&lt;/strong&gt;, so the architecture is ready for agents from day one.&lt;/p&gt;

Pick one recurring engineering chore (a weekly report, a dependency bump) and write it as an intent plus a done condition. If you can&apos;t state the done condition, an agent can&apos;t close the loop either.


- Chat assistants keep you as the copy-paste bridge. Agentic loops remove that step.
- MCP is the standard connector between agents and your tools.
- Keep MCP servers small and scoped to the task.
- Put a human sign-off between the plan and the action.
- The code might be generated, but the vision is still yours.

&lt;p&gt;If you want to move your team from chat prompts to scoped agent loops on Laravel and MCP, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams design and ship that stack&lt;/a&gt;, or &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;get in touch&lt;/a&gt; directly.&lt;/p&gt;
&lt;p&gt;Are you ready to stop writing code and start orchestrating your intent?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>vibe-coding</category><category>agentic-ai</category><category>mcp</category><category>claude</category><category>laravel</category><category>architecture</category></item><item><title>Monolith to microservices: a pragmatic guide</title><link>https://ansezz.com/blog/monolith-to-microservices/</link><guid isPermaLink="true">https://ansezz.com/blog/monolith-to-microservices/</guid><description>Skip the big-bang rewrite. The strangler fig pattern, anti-corruption layers, and Docker-first steps to move from monolith to microservices safely.</description><pubDate>Sun, 22 Feb 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;A big-bang rewrite can kill the business while the engineers play with new toys. Strangle the monolith one route at a time instead.&lt;/p&gt;

- The real problem is coupling, and jumping straight to microservices just moves those dependencies onto the network.
- The strangler fig pattern puts a routing layer in front, sends one endpoint at a time to a new service, and keeps the monolith as a safety net.
- Containerize the monolith first, protect new services with an anti-corruption layer, and split only when the monolith hurts more than the complexity tax.

&lt;p&gt;Your monolith is a ticking time bomb, and every feature you add brings the explosion closer.&lt;/p&gt;
&lt;p&gt;I have seen it happen a dozen times. A startup begins with a clean Laravel or Rails app. It is fast, easy and productive. Then the team grows and the code base swells.&lt;/p&gt;
&lt;h3&gt;When it starts to hurt&lt;/h3&gt;
&lt;p&gt;Suddenly, a simple change to the checkout logic breaks the authentication system. Deployments that used to take five minutes now take forty.&lt;/p&gt;
&lt;p&gt;You are no longer scaling your business. You are managing technical debt.&lt;/p&gt;
&lt;h3&gt;The distributed monolith trap&lt;/h3&gt;
&lt;p&gt;This is when most developers start dreaming of microservices: every service isolated, every deployment instant. The reality is often a nightmare.&lt;/p&gt;
&lt;p&gt;Do it wrong and you end up with a distributed monolith. You get all the complexity of networking with none of the benefits of isolation.&lt;/p&gt;
&lt;h3&gt;Pragmatic scaling&lt;/h3&gt;
&lt;p&gt;I skip the &quot;big bang&quot; rewrite and use the &lt;strong&gt;strangler fig pattern&lt;/strong&gt; to move from monoliths to microservices without losing my mind or my job.&lt;/p&gt;
&lt;p&gt;If you are still deciding whether to split at all, start with &lt;a href=&quot;https://ansezz.com/blog/monolith-vs-microservices/&quot;&gt;monolith vs microservices&lt;/a&gt;. This post assumes you have made that call and want the migration playbook.&lt;/p&gt;
&lt;h2&gt;The problem with the big bang&lt;/h2&gt;
&lt;p&gt;When a monolith gets too heavy, the first reaction is to scrap it. I have seen companies spend two years on a rewrite only to ship a product with half the features of the original.&lt;/p&gt;
&lt;h3&gt;Coupling is the enemy&lt;/h3&gt;
&lt;p&gt;The monolith is a phase. The real problem is coupling.&lt;/p&gt;
&lt;p&gt;When every part of your app knows too much about every other part, you cannot move. If you jump straight into microservices, you will likely port those dependencies into a network layer. Instead of a function call failing, you get a 500 error across a network socket.&lt;/p&gt;
&lt;h3&gt;Extract what hurts most&lt;/h3&gt;
&lt;p&gt;I prefer a slower, deliberate approach focused on high-value extractions. Look for the parts of the app that hurt the most.&lt;/p&gt;
&lt;p&gt;Is image processing slowing down the web server? Is the reporting engine locking up the database? Those are your first candidates for microservices.&lt;/p&gt;

List the three parts of your app that cause the most incidents or slow deploys. Pick the one with the fewest dependencies on the rest of the code as your first extraction.

&lt;h2&gt;The strangler fig pattern in practice&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://martinfowler.com/bliki/StranglerFigApplication.html&quot;&gt;Martin Fowler named this approach&lt;/a&gt; after a tree that grows around another tree. It starts as a small vine and eventually replaces the host entirely.&lt;/p&gt;
&lt;p&gt;In software, you build new features as services while the old monolith keeps running.&lt;/p&gt;
&lt;h3&gt;Put a router in front&lt;/h3&gt;
&lt;p&gt;The process starts with an API gateway or a load balancer. I put a routing layer in front: &lt;a href=&quot;https://www.nginx.com/&quot;&gt;Nginx&lt;/a&gt; or a &lt;a href=&quot;https://cloud.google.com/&quot;&gt;Google Cloud&lt;/a&gt; HTTP(S) load balancer with &lt;a href=&quot;https://cloud.google.com/armor&quot;&gt;Cloud Armor&lt;/a&gt; added for WAF and DDoS protection.&lt;/p&gt;
&lt;p&gt;If a request comes in for &lt;code&gt;/api/v1/orders&lt;/code&gt;, the URL map sends it to the new service. Everything else goes to the old monolith. (If you&apos;re unsure which box does what here, see &lt;a href=&quot;https://ansezz.com/blog/load-balancer-vs-api-gateway/&quot;&gt;load balancer vs API gateway&lt;/a&gt;.)&lt;/p&gt;
&lt;h3&gt;Flip back if it fails&lt;/h3&gt;
&lt;p&gt;This lets me test the new service in production with real traffic while the monolith acts as a safety net. If the new service fails, I flip the routing back.&lt;/p&gt;
&lt;p&gt;I don&apos;t have to migrate everything at once. I can migrate one endpoint at a time.&lt;/p&gt;
&lt;p&gt;Move one route, watch it under real traffic, and keep the old path one switch away.&lt;/p&gt;
&lt;figure&gt;

  &lt;div&gt;Freeze features, rebuild everything for months or years, then switch over in one risky launch.&lt;/div&gt;
  &lt;div&gt;Route one endpoint to a new service, prove it with real traffic, then move the next. The monolith shrinks while the business keeps shipping.&lt;/div&gt;

&lt;h2&gt;Containerization with Docker&lt;/h2&gt;
&lt;p&gt;You cannot do microservices without &lt;a href=&quot;https://www.docker.com/&quot;&gt;Docker&lt;/a&gt;. I treat every service as a black box.&lt;/p&gt;
&lt;p&gt;The monolith might run on an old version of PHP while the new service is a lean Go binary or a modern Laravel instance. Docker makes that possible.&lt;/p&gt;
&lt;h3&gt;Containerize the monolith first&lt;/h3&gt;
&lt;p&gt;I start by containerizing the monolith. Even if it stays a monolith for another year, the container forces me to define its environment and makes the infrastructure reproducible.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# a simplified example of a service container
FROM php:8.4-fpm

WORKDIR /app
COPY . /app

RUN apt-get update &amp;amp;&amp;amp; apt-get install -y \
    libpq-dev \
    &amp;amp;&amp;amp; docker-php-ext-install pdo_pgsql

EXPOSE 9000
CMD [&quot;php-fpm&quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Scale each service on its own&lt;/h3&gt;
&lt;p&gt;Once the monolith is containerized, I can deploy it to a platform like &lt;a href=&quot;https://cloud.google.com/kubernetes-engine&quot;&gt;Google Kubernetes Engine (GKE)&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;This is where microservices pay off. I can scale the order service to fifty instances during a sale while keeping the blog service at two.&lt;/p&gt;

Write a Dockerfile for your monolith as it is today and get it running locally with the same PHP version as production. That alone removes a class of &quot;works on my machine&quot; bugs.

&lt;h2&gt;Communication and the anti-corruption layer&lt;/h2&gt;
&lt;p&gt;The hardest part of microservices is the data, not the code. Your monolith has a single database, and your microservices should each have their own. So how do they talk?&lt;/p&gt;
&lt;h3&gt;Don&apos;t reach into the old database&lt;/h3&gt;
&lt;p&gt;I use an &lt;strong&gt;anti-corruption layer (ACL)&lt;/strong&gt;. When I extract a service, I don&apos;t let it reach back into the monolith&apos;s database. That would be cheating.&lt;/p&gt;
&lt;p&gt;Instead, I create an interface. If the new service needs user data, it asks the monolith through a private API or a message queue like &lt;a href=&quot;https://cloud.google.com/pubsub&quot;&gt;Google Pub/Sub&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;Keep the new service clean&lt;/h3&gt;
&lt;p&gt;The new service doesn&apos;t care about the legacy app&apos;s messy database schema. It only cares about the data it gets through the ACL.&lt;/p&gt;
&lt;p&gt;When the user logic is migrated later, I update the ACL to point to the new user service. For the asynchronous side (letting services react to events instead of calling each other directly), I lean on &lt;a href=&quot;https://ansezz.com/blog/event-driven-pubsub/&quot;&gt;event-driven Pub/Sub&lt;/a&gt; or &lt;a href=&quot;https://ansezz.com/blog/scaling-with-rabbitmq/&quot;&gt;a RabbitMQ-backed queue&lt;/a&gt;.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Cloud infrastructure and DevOps&lt;/h2&gt;
&lt;p&gt;Scaling a monolith usually means buying a bigger server. Scaling microservices means managing a fleet of small instances, so I rely on cloud-native tools to manage the complexity.&lt;/p&gt;
&lt;h3&gt;Infrastructure as code&lt;/h3&gt;
&lt;p&gt;I use &lt;a href=&quot;https://www.terraform.io/&quot;&gt;Terraform&lt;/a&gt; to manage my infrastructure as code. That keeps staging and production identical.&lt;/p&gt;
&lt;p&gt;If I need a new database for a service, I define it in code instead of clicking around a dashboard.&lt;/p&gt;
&lt;h3&gt;One pipeline per service&lt;/h3&gt;
&lt;p&gt;For deployments I use tools like &lt;a href=&quot;https://github.com/features/actions&quot;&gt;GitHub Actions&lt;/a&gt; or &lt;a href=&quot;https://coolify.io/&quot;&gt;Coolify&lt;/a&gt;. Every service has its own pipeline.&lt;/p&gt;
&lt;p&gt;If I update the checkout service, I only deploy the checkout service, without worrying about the rest of the system.&lt;/p&gt;
&lt;h2&gt;The hidden costs of microservices&lt;/h2&gt;
&lt;p&gt;I&apos;d be lying if I said this was all sunshine and rainbows. Microservices come with a &quot;complexity tax&quot;: distributed logging, service discovery and eventual consistency.&lt;/p&gt;
&lt;h3&gt;Only split when it hurts&lt;/h3&gt;
&lt;p&gt;My advice is to move to microservices only when the pain of the monolith is greater than the complexity tax. If your team is three people and your app is simple, stay in the monolith. You will move faster.&lt;/p&gt;
&lt;p&gt;If you are hitting walls every day and your developers are afraid to touch the code, it is time to start strangling.&lt;/p&gt;

- **Start with an API gateway** to handle routing.
- **Containerize your monolith first** to normalize the environment.
- **Use the strangler fig pattern** to migrate one domain at a time.
- **Build an anti-corruption layer** to keep new services clean.
- **Invest in infrastructure as code** early on.
- **Only split when the monolith starts to hurt** your productivity.

&lt;p&gt;Migration takes time. I have spent months on a single extraction to get it right, because the goal is a system that grows with your business, not a count of services. If you&apos;re planning that first extraction, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams move from a monolith to services without a rewrite&lt;/a&gt;, or &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;tell me about your migration&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Have you ever tried a &quot;big bang&quot; rewrite only to regret it six months later?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>microservices</category><category>scaling</category><category>docker</category><category>kubernetes</category><category>devops</category><category>laravel</category></item><item><title>AI vs traditional development: which fits?</title><link>https://ansezz.com/blog/ai-vs-traditional-development/</link><guid isPermaLink="true">https://ansezz.com/blog/ai-vs-traditional-development/</guid><description>AI vs traditional development: when AI-assisted speed pays off, when traditional engineering is non-negotiable, and the hybrid workflow I favor.</description><pubDate>Sun, 25 Jan 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;&quot;AI or traditional development?&quot; is the wrong question. The right one is how much speed, control and risk your business can afford.&lt;/p&gt;

- AI-assisted development wins on speed for known patterns: CRUD apps, admin panels, internal tools and first prototypes.
- Traditional engineering wins on control when business rules are complex, regulated or expensive to get wrong.
- Most teams should run a hybrid: AI drafts, humans own architecture, logic and the quality gates before merge.

&lt;p&gt;Most teams frame AI vs traditional development as a binary choice. That framing is the first mistake.&lt;/p&gt;
&lt;p&gt;I see it a lot. Teams chase AI because it feels faster, or reject it because it feels messy.&lt;/p&gt;
&lt;p&gt;Both directions land in the same place: rushed systems with weak foundations, or polished systems that ship too late.&lt;/p&gt;
&lt;p&gt;The better move is to understand where each approach wins, where it breaks and where a hybrid gives you the best return. Both work. They solve different problems.&lt;/p&gt;
&lt;h2&gt;AI-powered development: built for speed&lt;/h2&gt;
&lt;p&gt;AI changes how I build software. Instead of writing every repetitive piece by hand, I use tools that understand context, generate scaffolding, speed up testing and remove a lot of drag from delivery.&lt;/p&gt;
&lt;p&gt;I dig into the day-to-day of this in my post on &lt;a href=&quot;https://ansezz.com/blog/vibe-coding/&quot;&gt;vibe coding&lt;/a&gt;, where taste and intent matter more than raw typing speed.&lt;/p&gt;
&lt;h3&gt;The core advantage: speed&lt;/h3&gt;
&lt;p&gt;This is where AI shines.&lt;/p&gt;
&lt;p&gt;For standard workflows, admin panels, CRUD-heavy systems, internal tools and first-pass prototypes, AI can cut a serious amount of time. What used to take weeks can often shrink to days if the scope is clear and the review process is tight.&lt;/p&gt;
&lt;p&gt;That speed usually comes from a few places:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Automated code generation.&lt;/strong&gt; Prompts turn into usable boilerplate and feature drafts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Faster testing.&lt;/strong&gt; AI can draft test cases and edge-case coverage quickly.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Debugging support.&lt;/strong&gt; It helps narrow down likely failures faster.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Documentation help.&lt;/strong&gt; It turns rough implementation details into clean internal docs.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;How much of that speed you capture depends on where you sit on the &lt;a href=&quot;https://ansezz.com/blog/ai-coding-workflow-levels/&quot;&gt;AI coding workflow levels&lt;/a&gt;. Copy-pasting into a chat window and orchestrating agents against your real codebase are not the same tool.&lt;/p&gt;
&lt;h3&gt;Who benefits most from AI development&lt;/h3&gt;
&lt;p&gt;I lean toward AI-heavy workflows when speed matters more than perfect customization on day one. That usually means:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Startups trying to reach product-market fit before the runway gets tight.&lt;/li&gt;
&lt;li&gt;Small teams that need more output without more hires.&lt;/li&gt;
&lt;li&gt;Businesses shipping standard features that follow familiar patterns.&lt;/li&gt;
&lt;li&gt;Teams where non-technical stakeholders want to help with discovery and prototyping.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In those cases, AI acts like a power tool. It does not replace the builder. It makes the first cut much faster.&lt;/p&gt;

List the next five features on your roadmap and mark each one &quot;known pattern&quot; or &quot;custom logic.&quot; Start AI-heavy work only on the first group.

&lt;h2&gt;Where AI-first teams get burned&lt;/h2&gt;
&lt;p&gt;AI is fast at common patterns. It is weaker at deep product nuance, strange business rules and systems that need careful long-term architecture.&lt;/p&gt;
&lt;p&gt;If you skip review, you can ship something that looks finished but behaves like a prototype wearing a production costume.&lt;/p&gt;
&lt;h3&gt;Know which kind of AI you lean on&lt;/h3&gt;
&lt;p&gt;The trade-offs differ between predictive models and generative ones, which I break down in &lt;a href=&quot;https://ansezz.com/blog/ml-vs-genai/&quot;&gt;machine learning vs generative AI&lt;/a&gt;.&lt;/p&gt;
&lt;h3&gt;The debt bill arrives later&lt;/h3&gt;
&lt;p&gt;Some studies of AI-accelerated codebases report more duplicated code, larger pull requests and faster technical-debt buildup. The upfront speed can quietly shift effort into later debugging and rework.&lt;/p&gt;
&lt;p&gt;That is the trap. The fix is treating AI output as a draft, not as truth, the same discipline I argue for in &lt;a href=&quot;https://ansezz.com/blog/agentic-workflows-vibe-coding/&quot;&gt;the architectural shift to agentic workflows&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;AI output is a first draft. Review is what makes it a product.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Traditional development: the control champion&lt;/h2&gt;
&lt;p&gt;Traditional development is slower, but it gives me tighter control over how the system is shaped.&lt;/p&gt;
&lt;p&gt;This is the path I trust most when the business rules are complex, the architecture matters or the cost of failure is high. Every part of the system is designed with intent instead of inferred from a prompt.&lt;/p&gt;
&lt;h3&gt;The core advantage: control&lt;/h3&gt;
&lt;p&gt;Traditional development is better when the software needs precision. That matters for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Complex enterprise systems:&lt;/strong&gt; lots of moving parts and layered business logic.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Regulated industries:&lt;/strong&gt; where auditability and traceability matter.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Mission-critical applications:&lt;/strong&gt; where downtime or bad behavior is expensive.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Custom architectures:&lt;/strong&gt; where the product does not fit common patterns.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;The predictability factor&lt;/h3&gt;
&lt;p&gt;One underrated benefit of traditional development is predictability.&lt;/p&gt;
&lt;p&gt;Manual design, explicit code reviews, architecture decisions and planned testing give me a clearer picture of trade-offs. It is like building with blueprints instead of assembling furniture from a photo.&lt;/p&gt;
&lt;p&gt;That slower process often saves time later because fewer assumptions make it into production.&lt;/p&gt;
&lt;h3&gt;The time investment reality&lt;/h3&gt;
&lt;p&gt;The downside is obvious. Manual coding, reviews, debugging, refactoring and testing take time.&lt;/p&gt;
&lt;p&gt;You need stronger engineering talent, and the discipline to keep standards high when deadlines start squeezing the team. You pay for control in time and cost.&lt;/p&gt;
&lt;h2&gt;AI vs traditional development: head-to-head&lt;/h2&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Factor&lt;/th&gt;
&lt;th&gt;AI-assisted development&lt;/th&gt;
&lt;th&gt;Traditional development&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Upfront speed&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Often significantly faster&lt;/td&gt;
&lt;td&gt;Standard industry timelines&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Cost structure&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Cheaper to start, debt-prone later&lt;/td&gt;
&lt;td&gt;Higher labor cost, steadier&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Team requirements&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Still needs senior review&lt;/td&gt;
&lt;td&gt;Requires senior expertise&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Customization level&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Strong on common patterns&lt;/td&gt;
&lt;td&gt;Unlimited customization&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Quality assurance&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Fast drafts, human review required&lt;/td&gt;
&lt;td&gt;Manual review from the start&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Risk management&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Variable, depends on review rigor&lt;/td&gt;
&lt;td&gt;Predictable risk factors&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Scalability&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Scales output, not judgment&lt;/td&gt;
&lt;td&gt;Scales with team growth&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;Making the right choice for your business&lt;/h2&gt;
&lt;h3&gt;Choose AI integration when&lt;/h3&gt;
&lt;p&gt;Choose AI when your bottleneck is delivery speed and the work is close to known patterns. That usually applies when:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Your market window is tight.&lt;/li&gt;
&lt;li&gt;You are building standard business apps like portals, dashboards, e-commerce flows or content systems.&lt;/li&gt;
&lt;li&gt;Your team wants quick prototypes before committing engineering time.&lt;/li&gt;
&lt;li&gt;Your budget is better spent on iteration than on deep custom engineering from day one.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Choose traditional development when&lt;/h3&gt;
&lt;p&gt;Choose traditional development when the cost of being wrong is higher than the cost of being slower. That usually means:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The app needs a unique architecture.&lt;/li&gt;
&lt;li&gt;Compliance and audit trails are mandatory.&lt;/li&gt;
&lt;li&gt;Reliability matters more than release velocity.&lt;/li&gt;
&lt;li&gt;Your team wants direct ownership of code quality and system design.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;The hybrid strategy&lt;/h3&gt;
&lt;p&gt;This is the option I recommend most often. The strongest teams do not treat this like a religion. They use AI where speed helps and switch to traditional engineering where judgment matters.&lt;/p&gt;

  &lt;div&gt;Boilerplate and first drafts, prototypes, repetitive test scaffolding, first versions of docs and support material.&lt;/div&gt;
  &lt;div&gt;Reshaping drafts, rebuilding critical paths, logic and architecture review, and every final technical decision.&lt;/div&gt;

&lt;p&gt;The hybrid model works because it treats AI like a junior accelerator, not like an autopilot.&lt;/p&gt;

Write a one-line rule for your repo: which folders or modules AI may draft freely, and which ones always need a senior design review first. Put it in your contributing guide.

&lt;figure&gt;
&lt;h2&gt;Implementation guidelines&lt;/h2&gt;
&lt;h3&gt;Starting with AI integration&lt;/h3&gt;
&lt;p&gt;If I were introducing AI into an existing team, I would start small:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Begin with low-risk features.&lt;/li&gt;
&lt;li&gt;Define a review process for all AI-generated code, one that &lt;a href=&quot;https://ansezz.com/blog/stop-reading-code-ai-review/&quot;&gt;scales past line-by-line reading&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Choose tools that fit the current workflow.&lt;/li&gt;
&lt;li&gt;Train the team on prompting, verification and code quality checks.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Maintaining traditional excellence&lt;/h3&gt;
&lt;p&gt;If the team stays mostly traditional, I would protect the basics:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Invest in strong senior review.&lt;/li&gt;
&lt;li&gt;Keep documentation current.&lt;/li&gt;
&lt;li&gt;Use clear architecture standards.&lt;/li&gt;
&lt;li&gt;Avoid rushing complex work into fragile implementations.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Building hybrid capabilities&lt;/h3&gt;
&lt;p&gt;If the goal is balance, the workflow matters more than the tools:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Identify which tasks are repetitive and safe to automate.&lt;/li&gt;
&lt;li&gt;Keep humans responsible for architecture and business logic.&lt;/li&gt;
&lt;li&gt;Add quality gates before merge and deployment. &lt;a href=&quot;https://ansezz.com/blog/testing-ai-generated-code/&quot;&gt;Here is the gate I run on AI-authored PRs&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;Measure outcomes, not only speed.&lt;/li&gt;
&lt;/ul&gt;

Track two numbers for a month on AI-assisted pull requests: time to merge, and bugs found after merge. If the second number rises faster than the first falls, tighten your gates.

&lt;h2&gt;The future-ready approach&lt;/h2&gt;
&lt;p&gt;The teams that will win in 2026 are not the ones that blindly choose AI or reject it.&lt;/p&gt;
&lt;p&gt;They know where speed is enough, where control is non-negotiable and where a hybrid gives them speed without chaos.&lt;/p&gt;
&lt;p&gt;Use AI to remove friction. Use traditional engineering to protect the parts that matter. Combine both when the business needs speed and reliability at the same time.&lt;/p&gt;

- Pick by risk, not by trend: known patterns go AI-first, high-stakes logic stays human-led.
- AI speed comes with a debt bill if you skip review.
- Traditional engineering buys control and predictability at the cost of time.
- A hybrid with clear ownership and quality gates gives most teams the best return.

&lt;p&gt;Your development strategy should match your business goals, not the trend cycle. If you&apos;re deciding where AI belongs in your delivery process, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams pick and ship the right mix&lt;/a&gt;, or &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;reach out&lt;/a&gt; to talk it through.&lt;/p&gt;
&lt;p&gt;If you had to choose today, which matters more for your next product: speed, control or a hybrid path?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>architecture</category><category>ai</category><category>architecture</category><category>vibe-coding</category></item></channel></rss>