<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[KESTON Engineering]]></title><description><![CDATA[KESTON Engineering]]></description><link>https://keston-engineering.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 05 Dec 2026 00:08:06 GMT</lastBuildDate><atom:link href="https://keston-engineering.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Nginx and Linux Hardening for a Business Web App: A Working Checklist]]></title><description><![CDATA[Most compromised business sites I look at were not breached through a clever exploit. They were breached through a default config, an exposed admin path…]]></description><link>https://keston-engineering.hashnode.dev/nginx-and-linux-hardening-for-a-business-web-app-a-working-checklist</link><guid isPermaLink="true">https://keston-engineering.hashnode.dev/nginx-and-linux-hardening-for-a-business-web-app-a-working-checklist</guid><dc:creator><![CDATA[Leon]]></dc:creator><pubDate>Thu, 03 Dec 2026 06:21:18 GMT</pubDate><content:encoded><![CDATA[<p>Most compromised business sites I look at were not breached through a clever exploit. They were breached through a default config, an exposed admin path, or a service running as root because it was easier.</p>
<p>Here is the pass I run on a fresh box before it takes traffic.</p>
<h2>1. SSH first, because everything else depends on it</h2>
<pre><code class="language-ini">PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
AllowUsers deploy
</code></pre>
<p>Then <code>systemctl restart ssh</code>. Keep an existing session open while you test the new one — the most common self-inflicted outage in this checklist is locking yourself out.</p>
<p>Install fail2ban and point it at sshd. A few lines of jail config turns brute force from a nightly nuisance into a non-event.</p>
<h2>2. TLS that scores well without breaking clients</h2>
<p>Modern config, TLS 1.2 and 1.3 only, HSTS once you are sure about all subdomains:</p>
<pre><code class="language-nginx">ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_stapling on;
ssl_stapling_verify on;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
</code></pre>
<p>Renewal must be automated and monitored. A certificate that expires at 3am on a Saturday is an outage with a deadline you set yourself.</p>
<h2>3. Rate limits on the endpoints that matter</h2>
<p>Do not rate limit everything; you will break legitimate bursts. Limit login, password reset, and any endpoint that sends email or SMS.</p>
<pre><code class="language-nginx">limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;

location = /api/auth/login {
  limit_req zone=login burst=5 nodelay;
  proxy_pass http://app;
}
</code></pre>
<p>Pair it with a lockout counter in the application. Nginx protects the process; the app protects the account.</p>
<h2>4. Stop scanning noise before it reaches your app</h2>
<pre><code class="language-nginx">location ~ /\.(env|git|svn|hg) { deny all; return 404; }
location ~* \.(sql|bak|log|old|swp)$ { deny all; return 404; }
if ($request_uri ~* "(wp-admin|phpmyadmin|\.php$)") { return 404; }
</code></pre>
<p>If you do not run PHP, every request for a <code>.php</code> path is an attacker or a scanner. Answer 404 and move on.</p>
<h2>5. Run the app as a user that owns nothing else</h2>
<pre><code class="language-bash">useradd --system --no-create-home --shell /usr/sbin/nologin appsvc
chown -R appsvc:appsvc /srv/app
chmod -R u=rwX,g=rX,o= /srv/app
</code></pre>
<p>The <code>X</code> matters: directories get execute, files do not. Secrets belong in an environment file readable only by that user, not in the repo and not in the nginx config.</p>
<h2>6. Backups you have actually restored</h2>
<p>An untested backup is a rumour. Restore into a scratch database monthly and check row counts on the tables that matter. Encrypt the dump, keep it off the same host, and make sure the retention window matches the business requirement rather than the disk size.</p>
<h2>7. Logs that survive the incident</h2>
<p>Ship access and application logs off the box. If the attacker gets root, local logs are theirs to edit. A 7-day retention on the host plus 90 days off-host has caught more real problems for me than any SIEM.</p>
<h2>8. The five-minute check afterwards</h2>
<ul>
<li><code>ss -tulpn</code> — is anything listening that you did not expect?</li>
<li><code>lastb | head</code> — is anyone brute forcing?</li>
<li><code>systemctl list-units --state=failed</code> — anything broken and ignored?</li>
<li>certificate expiry date</li>
<li>a restore from last night's backup</li>
</ul>
<p>None of this is exotic. It is the difference between a server that survives being found and one that becomes a case study.</p>
<hr />
<p>The full checklist with the config files in one place: <a href="https://keston.dev/guides/server-security-hardening-for-business-web">https://keston.dev/guides/server-security-hardening-for-business-web</a></p>
<p>I do this hardening pass as part of every build at KESTON — <a href="https://keston.dev">https://keston.dev</a> — alongside the application work, because shipping a feature on an unhardened box is not shipping.</p>
]]></content:encoded></item><item><title><![CDATA[The Negative Balance Bug That Kills Multi-Tier Agent Systems]]></title><description><![CDATA[A multi-tier agent system is a commission ledger with a login page. Almost every bug I find in one is a ledger bug wearing a UI costume. The first mistake…]]></description><link>https://keston-engineering.hashnode.dev/the-negative-balance-bug-that-kills-multi-tier-agent-systems</link><guid isPermaLink="true">https://keston-engineering.hashnode.dev/the-negative-balance-bug-that-kills-multi-tier-agent-systems</guid><dc:creator><![CDATA[Leon]]></dc:creator><pubDate>Thu, 03 Dec 2026 06:20:30 GMT</pubDate><content:encoded><![CDATA[<p>A multi-tier agent system is a commission ledger with a login page. Almost every bug I find in one is a ledger bug wearing a UI costume.</p>
<h2>Balance is not a column</h2>
<p>The first mistake is storing <code>balance</code> as an integer column and updating it with <code>balance = balance - amount</code>. It works, until two withdrawal requests from the same agent arrive at the same millisecond and both read the same starting balance.</p>
<p>The fix is not a mutex in your Node process. It is either a conditional update or a serialized ledger:</p>
<pre><code class="language-sql">update agent_accounts
set balance_minor = balance_minor - $1
where agent_id = $2 and balance_minor &gt;= $1
returning balance_minor;
</code></pre>
<p>Zero rows returned means insufficient funds, decided by the database under a row lock. That single statement is the whole concurrency story. If you prefer an append-only ledger, the equivalent is inserting a debit row inside a transaction with a <code>select ... for update</code> on the account.</p>
<h2>Why append-only is worth the extra table</h2>
<p>An append-only ledger gives you three things a mutable balance cannot:</p>
<ul>
<li>a full audit trail that survives "who changed this number" questions</li>
<li>the ability to recompute balance and prove it matches</li>
<li>idempotent settlement, because a credit is a row with a unique reference</li>
</ul>
<pre><code class="language-sql">create table ledger_entries (
  id bigserial primary key,
  agent_id uuid not null,
  amount_minor bigint not null,        -- positive credit, negative debit
  kind text not null,                   -- commission | withdrawal | adjustment | reversal
  ref text not null,
  created_at timestamptz not null default now(),
  unique (agent_id, kind, ref)
);
</code></pre>
<p>The unique constraint is what makes settlement safe to retry. A commission job that crashes halfway and reruns will not double-pay, because the second insert for the same order reference fails and is skipped.</p>
<h2>The multi-tier part is where rounding bites</h2>
<p>Three tiers, 40% / 30% / 20%, and the platform keeps the remainder. On a 19.99 order the percentages produce fractions of a cent. If each tier rounds independently, the sum exceeds the order amount and the platform silently pays out more than it collected.</p>
<p>Allocate in integer minor units, sequentially, and give the remainder to the last tier or to the platform:</p>
<pre><code class="language-js">function split(amountMinor, rates) {
  const parts = [];
  let allocated = 0;
  for (const r of rates) {
    const part = Math.floor(amountMinor * r / 100);
    parts.push(part);
    allocated += part;
  }
  parts.push(amountMinor - allocated); // remainder to platform
  return parts;
}
</code></pre>
<p>Rounding down every tier and giving the remainder to the platform is a defensible policy. Rounding to nearest and hoping it adds up is not.</p>
<h2>RBAC: the checks people forget</h2>
<p>Role checks on the endpoint are the easy half. The bugs live in three other places:</p>
<ol>
<li><strong>Object-level authorization.</strong> An agent with the right role can still request <code>/api/agents/{id}/withdraw</code> for a different agent's id. Check ownership, not just role.</li>
<li><strong>Scope on lists.</strong> Filtering happens in the query, not in the UI. If your endpoint returns every agent and the frontend hides rows, you have a data leak.</li>
<li><strong>Privilege transitions.</strong> Demoting a manager must not leave their pending approvals actionable. Revoke or reassign on role change, in the same transaction.</li>
</ol>
<h2>Reversal, not deletion</h2>
<p>When a refund happens, insert a reversing entry. Never update or delete the original. The moment you delete a ledger row you lose the ability to answer a dispute, and you make reconciliation impossible.</p>
<hr />
<p>The full design, including the schema, the settlement job and the RBAC matrix, is here: <a href="https://keston.dev/guides/multi-agent-commission-admin-design">https://keston.dev/guides/multi-agent-commission-admin-design</a></p>
<p>I build these systems at KESTON — <a href="https://keston.dev">https://keston.dev</a> — multi-tier agent back offices with atomic commission settlement, negative-balance protection and full source handover.</p>
]]></content:encoded></item><item><title><![CDATA[Idempotency Keys: The Only Way to Survive Retried Payments]]></title><description><![CDATA[Every payment integration I have been asked to fix had the same latent bug: the charge endpoint was not idempotent. It works fine in testing. Then a mobile…]]></description><link>https://keston-engineering.hashnode.dev/idempotency-keys-the-only-way-to-survive-retried-payments</link><guid isPermaLink="true">https://keston-engineering.hashnode.dev/idempotency-keys-the-only-way-to-survive-retried-payments</guid><dc:creator><![CDATA[Leon]]></dc:creator><pubDate>Thu, 03 Dec 2026 06:19:42 GMT</pubDate><content:encoded><![CDATA[<p>Every payment integration I have been asked to fix had the same latent bug: the charge endpoint was not idempotent.</p>
<p>It works fine in testing. Then a mobile client loses signal after the request leaves the device but before the response arrives. The client retries. Now the customer has been charged twice, and the support ticket arrives before your monitoring does.</p>
<h2>Retries are the normal case, not the edge case</h2>
<p>A payment request can be retried by at least five different actors:</p>
<ul>
<li>the mobile SDK on a flaky network</li>
<li>the browser on a refresh</li>
<li>your own queue worker after a timeout</li>
<li>the payment gateway's webhook delivery</li>
<li>a human in the finance team clicking "charge again"</li>
</ul>
<p>If any of those can produce a second charge, your system is broken regardless of how good the gateway is.</p>
<h2>The key belongs to the client</h2>
<p>The idempotency key must be generated when the intent to pay is created, on the client, and reused for every retry of that same intent. A server-generated key per request defeats the purpose: the retry gets a fresh key and you are back to double charging.</p>
<pre><code class="language-js">// once, when the user taps Pay
const idempotencyKey = crypto.randomUUID();
// reused for every retry of this attempt
await fetch('/api/charge', {
  method: 'POST',
  headers: { 'Idempotency-Key': idempotencyKey },
  body: JSON.stringify({ orderId, amountMinor, currency }),
});
</code></pre>
<h2>Enforce it in the database, not in application code</h2>
<p>An <code>if (exists) return</code> check in your handler is a race condition with extra steps. Two concurrent requests both read "not exists" and both proceed. The only reliable enforcement is a unique constraint.</p>
<pre><code class="language-sql">create table charges (
  id uuid primary key default gen_random_uuid(),
  idempotency_key text not null,
  order_id uuid not null references orders(id),
  amount_minor bigint not null,
  currency char(3) not null,
  status text not null default 'pending',
  gateway_ref text,
  created_at timestamptz not null default now(),
  unique (idempotency_key)
);
</code></pre>
<p>Insert first, then call the gateway. If the insert violates the unique constraint, you already have a row for this key: read it and return the same response the original caller would have received. That is what idempotency means from the caller's point of view, not just "do not charge twice".</p>
<h2>The three failure modes that break naive implementations</h2>
<p><strong>1. Same key, different body.</strong> A retry should carry an identical payload. If the key matches but the amount or currency differs, do not silently return the old response. Return a 409 and log it: that pattern usually means a client bug or a tampering attempt.</p>
<p><strong>2. The gateway call succeeded but your process died before recording it.</strong> This is why you insert <code>pending</code> first and reconcile afterwards. Store the gateway reference as soon as you have it, and run a reconciliation job that asks the gateway about any charge stuck in <code>pending</code> for more than a few minutes. Never assume the absence of a response means the absence of a charge.</p>
<p><strong>3. The retry arrives after the row was cleaned up.</strong> Do not delete idempotency records on a short TTL. Keep them at least as long as the gateway keeps its own deduplication window, and longer than any client-side retry policy you ship.</p>
<h2>What the response should look like</h2>
<p>Store the response body alongside the row. On a duplicate, return the stored body with the original status code. Callers that retry should get an answer, not an error about a duplicate.</p>
<pre><code class="language-js">const existing = await db.charges.findByKey(key);
if (existing) {
  if (existing.request_hash !== hashOf(body)) return res.status(409).json({ error: 'key_reuse_mismatch' });
  return res.status(existing.response_status).json(existing.response_body);
}
</code></pre>
<h2>The part nobody tests</h2>
<p>Write the test before you ship: fire the same request twice concurrently, with the same key, and assert that the gateway received exactly one charge call. If your test suite cannot express that assertion, you do not know whether your system is idempotent.</p>
<hr />
<p>The longer version of this, including the settlement ledger and the multi-currency rounding rules that go with it, is in the architecture guide: <a href="https://keston.dev/guides/multilingual-multicurrency-shop-architecture">https://keston.dev/guides/multilingual-multicurrency-shop-architecture</a></p>
<p>I am Leon. I build cross-border storefronts, Telegram Mini Apps and multi-tier agent back offices at KESTON — <a href="https://keston.dev">https://keston.dev</a> — with milestone-based delivery and full source handover.</p>
]]></content:encoded></item><item><title><![CDATA[H5, uni-app or Native for Overseas Products: The Four Constraints That Actually Decide It]]></title><description><![CDATA[Originally published at keston.dev — H5, uni-app or native for overseas markets KESTON builds cross-border storefronts and cross-platform clients — H5…]]></description><link>https://keston-engineering.hashnode.dev/h5-uni-app-or-native-for-overseas-products-the-four-constraints-that-actually-decide-it</link><guid isPermaLink="true">https://keston-engineering.hashnode.dev/h5-uni-app-or-native-for-overseas-products-the-four-constraints-that-actually-decide-it</guid><dc:creator><![CDATA[Leon]]></dc:creator><pubDate>Thu, 03 Dec 2026 02:24:02 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p>Originally published at <a href="https://keston.dev/guides/h5-uniapp-vs-native-app-for-overseas?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=cross_platform">keston.dev — H5, uni-app or native for overseas markets</a></p>
<p>KESTON builds cross-border storefronts and cross-platform clients — H5, mini apps, iOS/Android shells and desktop — with USDT/USDC 50/50 milestones and 100% unencrypted Git handover.</p>
</blockquote>
<p>Every overseas product team hits the same fork in week one: <strong>ship one web build, wrap it in a native shell, or write two native apps?</strong> The answer is not a matter of taste. It is decided by four hard constraints — payments, push, hardware access, and app-store review — and by how much of your roadmap sits inside each of them.</p>
<p>I have shipped all three shapes for cross-border clients. Here is the decision matrix I actually use, and the traps that show up after launch rather than before it.</p>
<h2>The four constraints that decide it</h2>
<h3>1. Payments decide more than engineering</h3>
<p>If you sell physical goods with Stripe or a regional gateway (Adyen, Midtrans, Paystack, Mercado Pago), a web-based build is fine — the payment sheet is a hosted page or a native SDK with a JS bridge, and you stay clear of Apple's cut.</p>
<p>If you sell <strong>digital content or in-app features</strong>, Apple's App Store Review Guideline 3.1.1 applies the moment you distribute through the App Store: digital goods must use In-App Purchase, and IAP takes 15–30%. A "web shop inside an app" is the classic rejection. Either price the 30% in, or do not ship a native shell for that SKU at all.</p>
<p>That single line decides the architecture for a lot of teams, and it is usually discovered after the shell is built.</p>
<h3>2. Push notifications require a native shell, full stop</h3>
<p>Web Push works on Android Chrome and on iOS 16.4+ for <strong>installed</strong> PWAs (added to the home screen), and it is unreliable in the regions where a lot of cross-border traffic lives. If retention depends on push — order status, price drops, live chat replies — you need APNs and FCM, which means a real native shell.</p>
<p>A wrapped H5 build gets you this, but note the detail: with a plain WebView wrapper you must forward the token from native to your JS layer yourself. uni-app and React Native both ship plugins; a hand-rolled wrapper usually does not.</p>
<h3>3. Hardware access is where "just wrap it" fails</h3>
<p>Web APIs now cover camera (<code>getUserMedia</code>), geolocation, Bluetooth (Android Chrome only), and file access. They do not cover, reliably and cross-platform:</p>
<ul>
<li>background location and background sync</li>
<li>continuous barcode scanning at speed (a WebView scanner is visibly slower than MLKit/CameraX)</li>
<li>NFC, Bluetooth classic, USB/serial</li>
<li>reliable local persistence for offline-first flows</li>
</ul>
<p>If your app is "scan a code, upload a photo, show a list", web is enough. If scanning is the core loop, native camera pipelines win on every metric that matters to the user.</p>
<h3>4. Review cycles are a product constraint, not an ops detail</h3>
<p>A web build ships in minutes. A store build ships in 1–7 days, and a rejected build can cost a week. For a fast-moving cross-border operation — new market, new promo, new currency — a fully native shell means every copy change rides an app review.</p>
<p>The compromise most teams land on: <strong>native shell, remote-configurable content.</strong> Ship the container once; drive campaigns, copy and layout from your own backend.</p>
<h2>The realistic matrix</h2>
<table>
<thead>
<tr>
<th>Situation</th>
<th>Ship this</th>
<th>Why</th>
</tr>
</thead>
<tbody><tr>
<td>Marketing site, catalogue, lead forms</td>
<td>H5 / SSR web</td>
<td>no store friction, instant updates, best SEO</td>
</tr>
<tr>
<td>Cross-border storefront with Stripe + accounts</td>
<td>H5 first, PWA second</td>
<td>hosted checkout, no IAP exposure</td>
</tr>
<tr>
<td>Storefront that needs push and a home-screen icon</td>
<td>uni-app / Taro → native shell</td>
<td>one codebase, real APNs/FCM</td>
</tr>
<tr>
<td>Digital goods sold in-app</td>
<td>Native + IAP, or web-only</td>
<td>3.1.1 is not negotiable</td>
</tr>
<tr>
<td>Camera/scan/IM/audio-heavy</td>
<td>React Native or Flutter</td>
<td>native modules, predictable frame budget</td>
</tr>
<tr>
<td>Internal ops tool, desktop client</td>
<td>H5 + Electron/Tauri</td>
<td>reuse the web build</td>
</tr>
</tbody></table>
<p>Two rows cover most of what I get asked to quote. The expensive mistakes are always a team picking row 4 while their product is row 2, or picking row 3 for a product whose real loop is row 5.</p>
<h2>Traps that appear after launch, not before</h2>
<p><strong>WebView ≠ browser.</strong> iOS WKWebView and Android System WebView differ in <code>localStorage</code> limits, <code>IndexedDB</code> eviction under storage pressure, cookie behaviour in third-party contexts, and <code>postMessage</code> bridge performance. Code that is flawless in Chrome shows a white screen in a shell on one Android OEM. Budget a device matrix — a cheap Xiaomi, an older Samsung, an iPhone SE-class device, and one device in your actual target market.</p>
<p><strong>Cold-start white screen.</strong> A WebView shell that fetches your bundle over the network shows nothing for 2–4 seconds on a mid-range Android. Fix: bundle the shell locally, hydrate data after, and show a native splash with a real progress state. This is the single most common "it feels cheap" complaint.</p>
<p><strong>Deep links and <code>start_param</code>-style routing.</strong> Every campaign link must open the right screen. Test the cold-start path (app not running), the warm path, and the "app installed but logged out" path. All three break differently.</p>
<p><strong>Currency and locale in the shell.</strong> Formatting must follow the <em>market</em>, not the device locale — a user in Germany browsing your Indonesian store should see IDR, not EUR. Store integer minor units and a currency code; format at render.</p>
<p><strong>Safe areas and keyboards.</strong> iOS notch/home-indicator insets and Android keyboard resize modes will break fixed footers. Use <code>env(safe-area-inset-*)</code> and test with the keyboard open on both platforms.</p>
<p><strong>Update path.</strong> A wrapped build pins your JS version. If you cannot update it remotely, you have reintroduced the review cycle you were trying to escape. Either ship a remote bundle channel or accept the cadence deliberately.</p>
<h2>What it costs, honestly</h2>
<p>Rough shape from real quotes:</p>
<ul>
<li><strong>H5 only</strong> (storefront + checkout + account): 2–4 weeks for a focused build</li>
<li><strong>uni-app / Taro shell</strong> (one codebase, iOS + Android + H5, push, payment bridge): 3–6 weeks</li>
<li><strong>React Native / Flutter</strong> (native modules, offline, camera-heavy): 5–10 weeks</li>
<li><strong>Two true native codebases</strong>: roughly 1.6–1.9× the RN/Flutter figure, and two release trains forever</li>
</ul>
<p>The number that surprises people is not the build — it is the <em>maintenance multiplier</em>. A second codebase is not a one-time cost; it is a permanent second release train, second QA matrix, and second set of store listings.</p>
<h2>The rule I give clients</h2>
<p>Start from the constraint that would kill the business, not from the framework you like.</p>
<ul>
<li>If payments policy is the risk → web-first, native only for what must be native.</li>
<li>If retention is the risk → shell with push, and make content remote-configurable.</li>
<li>If the core loop is hardware → native, and stop trying to wrap it.</li>
</ul>
<p>Write the decision down with the constraint that drove it. In eighteen months, when someone proposes rewriting to the other shape, that sentence is what saves you a quarter.</p>
<hr />
<p><em>Leon is an independent full-stack engineer at <a href="https://keston.dev?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=cross_platform">KESTON</a> — cross-platform clients, cross-border storefronts and Telegram Mini Apps, delivered with USDT/USDC 50/50 milestones and full source handover. <a href="https://t.me/Leongodforu">Telegram</a> · <a href="mailto:hello@keston.dev">hello@keston.dev</a>. KESTON is a software studio and is not affiliated with Keston Boilers (UK).</em></p>
]]></content:encoded></item><item><title><![CDATA[The Multi-Level Agent Back Office Nobody Wants to Build: RBAC, Atomic Commission and Negative-Balance Proofing]]></title><description><![CDATA[Originally published at keston.dev — multi-level agent back office architecture Runnable companion code (11 tests, Node built-in sqlite)…]]></description><link>https://keston-engineering.hashnode.dev/the-multi-level-agent-back-office-nobody-wants-to-build-rbac-atomic-commission-and-negative-balance-proofing</link><guid isPermaLink="true">https://keston-engineering.hashnode.dev/the-multi-level-agent-back-office-nobody-wants-to-build-rbac-atomic-commission-and-negative-balance-proofing</guid><dc:creator><![CDATA[Leon]]></dc:creator><pubDate>Thu, 03 Dec 2026 02:18:21 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p>Originally published at <a href="https://keston.dev/guides/multi-agent-commission-admin-design?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=agent_rbac">keston.dev — multi-level agent back office architecture</a></p>
<p>Runnable companion code (11 tests, Node built-in sqlite): <a href="https://gist.github.com/Sundry007/8f493d691080f96c4d978c7369eb09c3">gist.github.com/Sundry007</a></p>
</blockquote>
<p>Every cross-border distribution business eventually asks for the same thing: a back office where agents recruit sub-agents, three levels of commission split automatically, and nobody can see or touch another agent's downline.</p>
<p>It sounds like a CRUD app. It is not. It is four hard problems wearing a dashboard:</p>
<ol>
<li><strong>Authorisation that follows the tree, not the user.</strong> A level-2 agent must see their own downline and nothing above it — and must not be able to <em>prove</em> they can't by probing IDs.</li>
<li><strong>Commission that is computed once and never recomputed.</strong> Retroactive rate changes are how you get disputes you cannot win.</li>
<li><strong>A balance that can never go negative</strong>, under concurrent withdrawals, without a distributed lock.</li>
<li><strong>An audit trail that survives an argument with an agent</strong>, which means every balance change carries a reason and an actor.</li>
</ol>
<p>This is the part of the project that agencies quote two weeks for and then disappear for two months. Below is how I build it.</p>
<h2>1. RBAC that is really row-level scoping</h2>
<p>The mistake is modelling roles as permissions: <code>agent_level_2: [view_orders, view_commission]</code>. Roles like that answer "what can you do" but not "on whose data", and the second question is the one that leaks.</p>
<p>The model that holds up:</p>
<ul>
<li>Every entity that belongs to an agent carries <code>owner_agent_id</code> and a materialised <code>path</code> (for example <code>/root/a1/a1-3/</code>).</li>
<li>An agent's visibility is a prefix match on <code>path</code>. A level-2 agent sees rows where <code>path LIKE '/root/a1/a1-3/%'</code>.</li>
<li>The scope is resolved <strong>server-side from the session</strong>, never from a request parameter. A client that sends <code>agent_id=someone_else</code> gets a 403, not a filtered list.</li>
</ul>
<p>The second rule is the one people skip. Filtering a list by a client-supplied ID is not authorisation, it is a suggestion. Authorisation is: the query is built from the session's own subtree, and the request body has no say in it.</p>
<p>For reads of a single record, scope checks must run before the record is serialised, and the 403 for "exists but not yours" must be indistinguishable from "does not exist" — otherwise the error code becomes an enumeration oracle.</p>
<h2>2. Commission: compute once, store forever</h2>
<p>Commission has three properties that must be designed in, not patched later:</p>
<ul>
<li><strong>Snapshot the rate.</strong> The rate row used for a settlement is copied into the commission record: <code>rate_bps</code>, <code>rate_source_id</code>, <code>rate_locked_at</code>. When finance changes the table next quarter, history does not move.</li>
<li><strong>Integer minor units only.</strong> Basis points against integer minor units, integer division with an explicit remainder policy. Floating point money is a bug you ship to production and discover in an audit.</li>
<li><strong>Deterministic split.</strong> For a three-level split of a total commission, the split must be computed with a documented remainder rule (largest-remainder or first-level-takes-remainder), because <code>100 * 0.6</code> style arithmetic leaves cents that must go <em>somewhere</em>. If the rule is not written down, two implementations will disagree and one of them will be in production.</li>
</ul>
<p>Then make settlement idempotent: a unique constraint on <code>(order_id, agent_id, level, settlement_batch)</code>. Re-running a batch is then a no-op instead of a double payout.</p>
<h2>3. Negative balance: atomic, not "usually fine"</h2>
<p>Withdrawal is where agent back offices get robbed. The naive flow — read balance, check <code>balance &gt;= amount</code>, insert withdrawal, update balance — is a race condition with a wide window under load.</p>
<p>Two implementations that hold up:</p>
<p><strong>Conditional update (preferred, no lock):</strong></p>
<pre><code class="language-sql">UPDATE agent_balance
   SET balance = balance - :amount, updated_at = now()
 WHERE agent_id = :agent_id
   AND balance &gt;= :amount
RETURNING balance;
</code></pre>
<p>Zero rows returned means insufficient funds — the check and the decrement are the same statement. No read-modify-write window exists.</p>
<p><strong>Ledger with a materialised balance</strong>, where every change is an append-only row (<code>amount</code>, <code>reason</code>, <code>ref_id</code>, <code>actor</code>) and the balance is a derived cache updated in the same transaction. This gives you the audit trail <em>and</em> the invariant: <code>sum(ledger.amount) == agent_balance.balance</code> becomes a reconciliation query you can run nightly and alert on.</p>
<p>If your stack forces you into an explicit lock, lock in a deterministic order (by <code>agent_id</code> ascending) so two concurrent transfers cannot deadlock each other.</p>
<h2>4. The audit trail is a product feature</h2>
<p>Agents argue about money. The back office either settles the argument in one query or loses the agent. So every balance movement stores: who did it, what caused it (order settlement, withdrawal, manual adjustment), which order or batch, and the rate snapshot used.</p>
<p>Manual adjustments get a required note field. It is the field developers try to skip and the field support uses every week.</p>
<h2>What I actually ship</h2>
<p>A working multi-level agent back office is roughly: the tree model with materialised paths, scope-from-session middleware, an append-only ledger with a conditional-update balance, idempotent settlement batches, an admin surface for rate changes that never rewrites history, and a reconciliation job.</p>
<p>I published the SQL shape for the ledger, the conditional decrement and the idempotency constraints as a runnable gist with a 10-case test suite: <a href="https://gist.github.com/Sundry007/27429618e881bfd92545">multi-level commission ledger on GitHub Gist</a>.</p>
<p>The full design write-up — tree scoping, split remainder rules, settlement batches, reconciliation — is here: <a href="https://keston.dev/guides/multi-agent-commission-admin-design?utm_source=devto&amp;utm_medium=article&amp;utm_campaign=agent_rbac">multi-level agent commission admin design</a>. The build service is <a href="https://keston.dev/solutions/enterprise-admin-crm?utm_source=devto&amp;utm_medium=article&amp;utm_campaign=agent_rbac">enterprise admin / CRM systems</a>, with <a href="https://keston.dev/pricing?utm_source=devto&amp;utm_medium=article&amp;utm_campaign=agent_rbac">fixed-scope pricing</a> and full source handover.</p>
<p><em>I'm Leon, an independent full-stack engineer running KESTON — unrelated to Keston Boilers, the UK heating brand. I build cross-border storefronts, agent back offices, Telegram Mini Apps and multilingual support desks.</em></p>
]]></content:encoded></item><item><title><![CDATA[Your AI Support Bot Will Refund Money It Should Never Refund: A 19-Locale Routing Layer]]></title><description><![CDATA[Originally published at keston.dev — multilingual AI support architecture Every multilingual support bot demo looks the same: you type "where is my order"…]]></description><link>https://keston-engineering.hashnode.dev/your-ai-support-bot-will-refund-money-it-should-never-refund-a-19-locale-routing-layer</link><guid isPermaLink="true">https://keston-engineering.hashnode.dev/your-ai-support-bot-will-refund-money-it-should-never-refund-a-19-locale-routing-layer</guid><dc:creator><![CDATA[Leon]]></dc:creator><pubDate>Thu, 03 Dec 2026 02:03:21 GMT</pubDate><content:encoded><![CDATA[<blockquote>
<p>Originally published at <a href="https://keston.dev/guides/ai-multilingual-live-chat-system?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=ai_support_router">keston.dev — multilingual AI support architecture</a></p>
</blockquote>
<p>Every multilingual support bot demo looks the same: you type "where is my order", it answers in your language, everyone claps. Then it goes live, and within a week three things happen that no demo ever shows.</p>
<p><strong>It refunds money.</strong> A customer writes "I want my money back or I call my lawyer" in Turkish. The model, being helpful, apologises and promises a refund. Your finance team finds out from the chargeback.</p>
<p><strong>It invents policy.</strong> Your refund rules were reviewed in English, Traditional Chinese, Japanese and Korean. The bot happily paraphrases them in Polish, where nobody has ever read the actual terms. The translation is fluent. It is also wrong.</p>
<p><strong>It burns a budget.</strong> One customer in a loop, 40 messages, a reasoning-tier model on every turn. A single conversation costs more than the order.</p>
<p>None of these are model-quality problems. They are <strong>routing</strong> problems: what reaches the model, in which locale, under what budget. Fix the routing and a mid-tier model becomes shippable. Skip it and the best model on the market still refunds money it should never refund.</p>
<h2>The decision layer, not the prompt</h2>
<p>The instinct is to write a longer system prompt: "never promise refunds, never discuss legal matters, always stay in policy". This fails for a structural reason — a prompt is a suggestion evaluated by the same model that is trying to be helpful. A routing layer is code, and code can be tested, logged and audited.</p>
<p>So the architecture is:</p>
<pre><code>inbound message
      │
      ▼
[ guard table ]  ── money / legal / security / finance ──▶ human queue (priority 80-100)
      │
      ▼
[ value + sentiment + loop checks ] ─────────────────────▶ human queue (priority 50-70)
      │
      ▼
[ locale policy gate ] ── locale has no reviewed strings ─▶ human queue (priority 50)
      │
      ▼
[ token budget ] ── exhausted ────────────────────────────▶ stop
      │
      ▼
   model tier chosen by locale + intent
</code></pre>
<p>Three properties matter more than the exact rules:</p>
<ol>
<li><strong>Deterministic.</strong> Same message, same decision. No sampling, no clock, no randomness. This is what makes the layer unit-testable.</li>
<li><strong>Fail closed.</strong> Any uncertainty — unknown locale, high order value, unreviewed policy — escalates to a human instead of guessing.</li>
<li><strong>Cheap to run.</strong> The guard table is regex and arithmetic. It costs microseconds and runs before you spend a token.</li>
</ol>
<h2>Guard table: the four things a bot must never handle</h2>
<p>These four intents are not "hard questions". They are intents where a wrong answer creates a liability that outlives the conversation:</p>
<table>
<thead>
<tr>
<th>Intent</th>
<th>Signal</th>
<th>Why escalation</th>
</tr>
</thead>
<tbody><tr>
<td>Money movement</td>
<td>refund, chargeback, dispute (in any of the 19 locales)</td>
<td>a promised refund is a financial commitment</td>
</tr>
<tr>
<td>Legal exposure</td>
<td>lawyer, solicitor, sue, consumer protection</td>
<td>anything said becomes evidence</td>
</tr>
<tr>
<td>Account security</td>
<td>hacked, unauthorised login, 2FA loss</td>
<td>an unauthenticated bot must not touch credentials</td>
</tr>
<tr>
<td>Tax documents</td>
<td>invoice, VAT, tax id, receipt</td>
<td>finance generates documents, not a language model</td>
</tr>
</tbody></table>
<p>Order matters. A message containing both "refund" and "where is my order" is a refund message. Highest-priority rule wins, and the winning rule is written to the conversation record so a human can see <em>why</em> it escalated.</p>
<p>The multilingual part is the tedious part: each intent needs its trigger set in every supported locale. A refund keyword list that only covers English and Spanish will quietly pass German refund demands straight to the model. In the routing module I published, every rule carries its triggers across 19 locales — including Japanese, Korean, Thai, Vietnamese, Turkish and Arabic.</p>
<h2>The locale gate nobody builds</h2>
<p>Here is the failure I see most often in cross-border deployments. The site supports 19 locales for <em>marketing</em>. Someone assumes the same 19 locales are ready for <em>policy</em> conversation. They are not: marketing copy is reviewed by a marketer, refund policy is reviewed by whoever owns the money.</p>
<p>So the routing layer needs an explicit allowlist of locales whose customer-facing policy strings have been human-reviewed. A message in a locale outside that list does not get a translated guess. It goes to a human queue with the locale attached, so the team can see exactly which market is generating unreviewed traffic — which is also your queue for hiring the next reviewer.</p>
<p>This single check converts "we support 19 languages" from a liability into a roadmap.</p>
<h2>Cost: budget per conversation, not per month</h2>
<p>Monthly token budgets are useless for support, because cost is concentrated: a handful of looping conversations dominate the bill. The unit that matters is the conversation.</p>
<p>Give each conversation a hard token budget. When it is spent, the layer stops the bot and hands over — it does not "try once more with a cheaper model". A stop is honest; a downgraded answer to an already frustrated customer is not.</p>
<p>Then attribute spend: per conversation, per tenant, per locale. Without attribution you cannot answer the only commercial question that matters — is this locale's automation actually cheaper than staffing it?</p>
<h2>Model tiers by locale, not by prestige</h2>
<p>Not every locale deserves the most expensive model on the first turn. In practice three tiers cover the traffic:</p>
<ul>
<li><strong>standard tier</strong> — your highest-volume, best-reviewed locales (English, Traditional Chinese, Japanese)</li>
<li><strong>multilingual tier</strong> — locales where the smaller model's fluency is already adequate for FAQ and logistics traffic</li>
<li><strong>reasoning tier</strong> — technical intents (error reports, integration questions) and long messages, regardless of locale</li>
</ul>
<p>Technical intent and message length are better predictors of "needs the expensive model" than language is. A 1,200-character error report in Vietnamese needs reasoning. A one-line "where is my parcel" in English does not.</p>
<h2>What you get to test</h2>
<p>Because the layer is pure, the test suite is boring and fast: 15 cases, no network, no model. Refund in English escalates. Refund in Traditional Chinese escalates. Legal threat escalates. Account takeover escalates. FAQ goes to the AI tier. Unreviewed locale escalates instead of inventing policy. High-value order escalates. Two negative turns escalate. Three unresolved turns escalate. Budget exhausted stops. Same input, same output, twice.</p>
<p>That suite is the actual deliverable. It is what lets you change a prompt, swap a model or add a locale without re-auditing the whole desk — the safety properties live in code, not in the prompt you just edited.</p>
<p>The full runnable module and its test suite are published here: <a href="https://gist.github.com/Sundry007/ef67fbfed756abcd056062b450a1dd6e">multilingual AI support routing on GitHub Gist</a>.</p>
<h2>Where this fits commercially</h2>
<p>A support bot is not a chatbot project; it is an escalation design. The work is deciding what never reaches the model, which locales are allowed to answer, and how a conversation ends. Build that first and the model choice becomes a line item you can tune. Build the model first and you will spend the next quarter firefighting refunds.</p>
<p>If you are shipping a multilingual support desk and want the routing layer, the locale policy audit and the human hand-off built as one system — <a href="https://keston.dev/guides/ai-multilingual-live-chat-system?utm_source=devto&amp;utm_medium=article&amp;utm_campaign=ai_support_router">the architecture write-up is here</a>, and the <a href="https://keston.dev/solutions/ai-customer-service-automation?utm_source=devto&amp;utm_medium=article&amp;utm_campaign=ai_support_router">AI customer service automation service page</a> covers scope and delivery. Fixed-scope pricing, milestone settlement, full source handover: <a href="https://keston.dev/pricing?utm_source=devto&amp;utm_medium=article&amp;utm_campaign=ai_support_router">keston.dev/pricing</a>.</p>
<p><em>I'm Leon, an independent full-stack engineer running KESTON — unrelated to Keston Boilers, the UK heating brand. I build cross-border storefronts, Telegram Mini Apps, multi-level agent back offices and multilingual AI support desks, with an AI-assisted pipeline that ships in weeks rather than quarters.</em></p>
]]></content:encoded></item><item><title><![CDATA[Integer Money, Locked FX Rates and Idempotent Webhooks: What a Multi-Currency Storefront Really Needs]]></title><description><![CDATA[Why cross-border checkouts drift: integer minor units, FX rate snapshots per order, idempotent webhooks, basis-point commission splits.]]></description><link>https://keston-engineering.hashnode.dev/integer-money-locked-fx-rates-and-idempotent-webhooks-what-a-multi-currency-storefront-really-needs</link><guid isPermaLink="true">https://keston-engineering.hashnode.dev/integer-money-locked-fx-rates-and-idempotent-webhooks-what-a-multi-currency-storefront-really-needs</guid><category><![CDATA[ecommerce]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[postgres]]></category><category><![CDATA[architecture]]></category><dc:creator><![CDATA[Leon]]></dc:creator><pubDate>Thu, 03 Dec 2026 00:18:40 GMT</pubDate><content:encoded><![CDATA[<p>Cross-border storefronts rarely break because of a missing feature. They break because of arithmetic.</p>
<p>I have rebuilt enough multi-currency checkouts to know the pattern: the demo works in one currency, the first real order arrives in another, and six weeks later finance finds a 0.4% hole in the reconciliation report that nobody can explain. The cause is almost always one of three things — floating point money, an FX rate that gets re-read at refund time, or a payment webhook that fires twice.</p>
<p>This is a short, practical breakdown of how to make all three impossible by design.</p>
<h2>1. Money is an integer, and the currency is part of the number</h2>
<p>Store every amount as an integer in the currency's minor unit, with an explicit scale — JPY and KRW have 0 decimals, most others have 2, and a few have 3. Never <code>number</code>/<code>float</code>/<code>double</code>. A single <code>0.1 + 0.2</code> in a settlement path is a bug that survives code review because it looks correct in the debugger.</p>
<pre><code class="language-js">const SCALE = { USD: 2, EUR: 2, JPY: 0, KWD: 3 };

function toMinor(amount, currency) {
  const s = SCALE[currency];
  if (s === undefined) throw new Error('unsupported currency');
  return Math.round(Number(amount) * 10 ** s);
}

function fromMinor(minor, currency) {
  return Number(minor) / 10 ** SCALE[currency];
}
</code></pre>
<p>The important discipline is that the scale travels with the value. A bare integer column without a currency code is an invitation for a future developer to sum two different units.</p>
<h2>2. Lock the FX rate on the order, not on the request</h2>
<p>If your checkout reads the rate from a provider at payment time, then reads it again at refund time, you have invented a currency position. You are now exposed to whatever moved in between, and the loss lands on the merchant.</p>
<p>The fix: snapshot the rate and its provenance onto the order row at creation.</p>
<pre><code class="language-sql">ALTER TABLE orders
  ADD COLUMN fx_rate      NUMERIC(20,10) NOT NULL,
  ADD COLUMN fx_base      CHAR(3)        NOT NULL,
  ADD COLUMN fx_quote     CHAR(3)        NOT NULL,
  ADD COLUMN fx_source    TEXT           NOT NULL,
  ADD COLUMN fx_locked_at TIMESTAMPTZ    NOT NULL DEFAULT now();
</code></pre>
<p>Every downstream operation — refund, partial refund, chargeback, partner commission — converts using the order's stored rate. Refunds are then exact by construction: the customer gets back precisely the amount they were charged, in the currency they were charged.</p>
<p>Store the rate as a fixed-point decimal, not a float. <code>NUMERIC(20,10)</code> gives you enough precision for any realistic pair, and PostgreSQL will not silently round it.</p>
<h2>3. Every webhook needs an idempotency key and a unique constraint</h2>
<p>Stripe retries. Telegram retries. Chain indexers replay blocks. If your handler credits a balance without a deduplication guard, the customer gets paid twice and you find out a week later.</p>
<p>The guard belongs in the database, not in application memory — an in-process <code>Set</code> dies on restart and does not survive a second replica.</p>
<pre><code class="language-sql">CREATE TABLE payment_events (
  id             BIGSERIAL PRIMARY KEY,
  provider       TEXT NOT NULL,
  provider_event TEXT NOT NULL,
  order_id       BIGINT NOT NULL REFERENCES orders(id),
  received_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
  UNIQUE (provider, provider_event)
);
</code></pre>
<p>Then the credit and the event insert happen in one transaction:</p>
<pre><code class="language-sql">BEGIN;
INSERT INTO payment_events (provider, provider_event, order_id)
VALUES ('stripe', 'evt_1Qx...', 4211)
ON CONFLICT (provider, provider_event) DO NOTHING;

-- only credit when the insert actually happened
UPDATE order_balances b
   SET paid_minor = b.paid_minor + 129900
  FROM payment_events e
 WHERE e.provider = 'stripe'
   AND e.provider_event = 'evt_1Qx...'
   AND b.order_id = e.order_id
   AND e.received_at &gt; now() - interval '5 seconds';
COMMIT;
</code></pre>
<p>The <code>received_at</code> window is a cheap way to make the second execution a no-op without a second round trip. Combined with a row-level lock on the balance, concurrent duplicates cannot both win.</p>
<h2>4. Split commission in basis points, never in percentages</h2>
<p>Partner payouts are where rounding gets expensive. If three levels take 10% / 5% / 2% and you round each one independently, the remainders either vanish or double-count, and the ledger stops balancing.</p>
<p>Work in basis points (integers), require the total to be exactly 10000, and distribute the remainder by largest remainder so the sum always equals the total:</p>
<pre><code class="language-js">function splitMinor(total, bpsList) {
  const sum = bpsList.reduce((a, b) =&gt; a + b, 0);
  if (sum !== 10000) throw new Error('rates must sum to 10000 bps');
  const base = Math.floor(total / 10000);
  const rem = total % 10000;
  const raw = bpsList.map((bps) =&gt; base * bps);
  const fractions = bpsList.map((bps) =&gt; (rem * bps) % 10000);
  let left = total - raw.reduce((a, b) =&gt; a + b, 0);
  const order = fractions.map((f, i) =&gt; [f, i]).sort((a, b) =&gt; b[0] - a[0]);
  for (let k = 0; k &lt; order.length &amp;&amp; left &gt; 0; k += 1) {
    raw[order[k][1]] += 1;
    left -= 1;
  }
  return raw;
}
</code></pre>
<p>This function is a test fixture magnet — assert that the outputs always sum back to <code>total</code> for a few thousand random inputs, and you will never see a drifting ledger again.</p>
<h2>5. Make the partner tree a query, not a crawl</h2>
<p>Multi-level referral systems get slow and wrong in the same way: the code walks parent pointers in application memory, one query per level. At three levels that is tolerable; at six it is a timeout, and at any depth it is a race condition when a partner is reassigned mid-request.</p>
<p>A recursive CTE keeps the traversal in the database, inside one transaction, with a depth cap:</p>
<pre><code class="language-sql">WITH RECURSIVE chain AS (
  SELECT id, parent_id, 0 AS depth FROM partners WHERE id = $1
  UNION ALL
  SELECT p.id, p.parent_id, c.depth + 1
    FROM partners p JOIN chain c ON p.id = c.parent_id
   WHERE c.depth &lt; 8
)
SELECT id, depth FROM chain ORDER BY depth;
</code></pre>
<p>Pair it with a <code>UNIQUE</code> constraint that prevents a partner from appearing twice in one chain, and a depth limit enforced in the schema, and the "infinite loop because someone set A's parent to B while B's parent is A" incident never happens.</p>
<h2>6. What this costs to get right</h2>
<p>None of the above is exotic. It is roughly two extra days of schema work on a mid-sized storefront, and it is the difference between a system that survives its first month of real volume and one that produces a reconciliation spreadsheet nobody trusts.</p>
<p>If you are scoping a cross-border build, the useful question is not "how many pages" but "who owns the ledger". A quote that does not mention idempotency keys, an FX snapshot column and integer minor units is a quote for a demo.</p>
<hr />
<p><em>Full runnable reference implementation (integer ledger, FX lock, idempotent webhook):</em> <a href="https://gist.github.com/Sundry007/a7342f259687393dce0f8d9434ee3ded"><em>gist.github.com/Sundry007/a7342f259687393dce0f8d9434ee3ded</em></a></p>
<p><strong>Further reading</strong></p>
<ul>
<li><a href="https://keston.dev/guides/multilingual-multicurrency-shop-architecture?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=multicurrency-ledger">Multi-currency storefront architecture</a></li>
<li><a href="https://keston.dev/solutions/cross-border-ecommerce?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=multicurrency-ledger">Cross-border e-commerce engineering</a></li>
<li><a href="https://keston.dev/pricing?utm_source=hashnode&amp;utm_medium=article&amp;utm_campaign=multicurrency-ledger">Fixed-scope, per-milestone pricing</a></li>
</ul>
<p><em>KESTON (keston.dev) is an independent full-stack software studio — no relation to Keston Boilers, the UK heating brand. Builds are quoted per milestone, delivered with full unencrypted Git source handover, and settled 50/50 in USDT/USDC.</em></p>
]]></content:encoded></item></channel></rss>