<?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[eSIMCircle Travel Connectivity]]></title><description><![CDATA[eSIMCircle Travel Connectivity]]></description><link>https://esimcircle.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Fri, 04 Dec 2026 22:46:14 GMT</lastBuildDate><atom:link href="https://esimcircle.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Home-Routed vs Local Breakout Roaming: Where Your Data Exits]]></title><description><![CDATA[Picture two travellers in the same airport with data roaming on. One sees 40 ms to a local server, the other 280 ms and a website that thinks they are…]]></description><link>https://esimcircle.hashnode.dev/home-routed-vs-local-breakout-roaming-where-your-data-exits</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/home-routed-vs-local-breakout-roaming-where-your-data-exits</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Fri, 04 Dec 2026 08:45:28 GMT</pubDate><content:encoded><![CDATA[<p>Picture two travellers in the same airport with data roaming on. One sees 40 ms to a local server, the other 280 ms and a website that thinks they are still at home. Radio signal is often not the difference. The difference is <strong>home-routed vs local breakout roaming</strong>: where the user plane leaves the mobile core and reaches the internet.</p>
<p><img src="https://images.pexels.com/photos/36359722/pexels-photo-36359722/free-photo-of-tall-cellular-tower-against-a-clear-blue-sky.jpeg?auto=compress&amp;cs=tinysrgb&amp;w=1200" alt="Cellular tower with antennas against a clear blue sky" /></p>
<h2>Home-routed vs local breakout roaming in one picture</h2>
<p>When you roam, two networks are involved: the home network (HPLMN), which owns your subscription, and the visited network (VPLMN), which owns the radio you are camped on.</p>
<pre><code class="language-text">Home-routed (LTE)
UE -&gt; eNodeB -&gt; SGW (visited) ==S8==&gt; PGW (home) -&gt; Internet

Local breakout (LTE)
UE -&gt; eNodeB -&gt; SGW (visited) -&gt; PGW (visited) -&gt; Internet
</code></pre>
<p>In the first design your packets are tunnelled back to a gateway owned by (or operated for) your home provider. In the second they exit in the visited country. In both cases, authentication still involves the home subscriber database.</p>
<h2>The same idea in 5G</h2>
<p>With a 5G core, the names change but the choice does not. In home-routed roaming, a visited UPF (V-UPF) connects over the N9 interface to a home UPF (H-UPF), which is the PDU session anchor. In local breakout, the anchor UPF sits in the visited network. The architectures are specified in <a href="https://www.3gpp.org/DynaReport/23401.htm">3GPP TS 23.401</a> for EPC and <a href="https://www.3gpp.org/DynaReport/23501.htm">3GPP TS 23.501</a> for the 5G system. Commercial arrangements between operators follow GSMA roaming guidelines.</p>
<p>Note that many consumer data roaming deployments are home-routed. Do not assume local breakout just because you are abroad.</p>
<h2>What the anchor decides</h2>
<p>The gateway that anchors the session has a large effect on what applications see:</p>
<ul>
<li><strong>Public IP geolocation.</strong> Services see the country of the egress point, which may differ from where you are standing.</li>
<li><strong>Latency.</strong> Packets travel to the anchor first, then to the server. A distant anchor adds a round trip across continents even for a nearby server.</li>
<li><strong>Content and licensing.</strong> Streaming catalogues, bank fraud checks and payment pages often key off the IP address.</li>
<li><strong>DNS.</strong> The resolver handed out with the session usually belongs to the anchor side, so CDN selection follows it.</li>
<li><strong>Policy.</strong> Filtering, traffic shaping and tethering rules are commonly enforced there.</li>
</ul>
<h2>The eSIM twist</h2>
<p>An eSIM only changes how a profile reaches the eUICC. It does not decide routing. A travel eSIM is often itself a roaming subscription: the profile's home operator may be in a third country, and the local network you attach to is the visited one. That is why a plan bought for one destination can show an IP address from somewhere else. It is normal behaviour, not necessarily a fault.</p>
<p><img src="https://images.pexels.com/photos/36247361/pexels-photo-36247361/free-photo-of-close-up-of-cellular-tower-against-blue-sky.jpeg?auto=compress&amp;cs=tinysrgb&amp;w=1200" alt="Close-up of a modern cellular tower against a vivid blue sky" /></p>
<h2>How to tell which one you have</h2>
<p>You cannot read the interface names from a phone, but you can infer the egress point:</p>
<ol>
<li>Turn Wi-Fi off and make sure the intended line is selected for data.</li>
<li>Look up your public IP and note its registered country and network.</li>
<li>Compare latency to a nearby server and to one in the suspected anchor country.</li>
</ol>
<pre><code class="language-bash"># run from a laptop tethered to the phone
curl -s https://ipinfo.io/json
ping -c 10 1.1.1.1
traceroute example.com
</code></pre>
<p>Read the results with care. Anycast addresses such as 1.1.1.1 answer from a nearby edge of the egress point, geolocation databases can be stale, and mobile cores often hide hops from traceroute. One measurement is a hint, not proof.</p>
<h2>Troubleshooting checklist</h2>
<ul>
<li><strong>No data at all:</strong> check data roaming is on for that line and that the APN matches what the provider specifies.</li>
<li><strong>Connected but slow:</strong> try manual network selection. Another partner network can give better radio, though the anchor may stay the same.</li>
<li><strong>Site thinks you are elsewhere:</strong> expected with a remote anchor; use the site's country selector where offered.</li>
<li><strong>VPN unstable:</strong> nested tunnels reduce the usable MTU. Lower the VPN MTU or try a TCP-friendly profile.</li>
<li><strong>Voice or SMS differs from data:</strong> voice roaming uses IMS arrangements that are separate from the internet APN.</li>
</ul>
<h2>Which should you prefer?</h2>
<p>Home-routed gives the operator consistent policy and billing, and gives you a predictable exit point. Local breakout usually wins on latency. For maps and messaging, either is fine. For video calls, gaming or remote desktop, latency matters, so test early rather than assuming.</p>
<p><strong>Practical advice:</strong> before a work trip, record your public IP and round-trip time on day one. If something breaks later, you have a baseline. If you want a data line to experiment with, you can <a href="https://esimcircle.com/esims/singapore-esim/">compare Singapore eSIM plans on eSIMCircle</a> and check the plan details before buying.</p>
]]></content:encoded></item><item><title><![CDATA[Inside IMS Registration for VoLTE Roaming: S8HR vs Local Breakout, P-CSCF Discovery and SIP Flows]]></title><description><![CDATA[When a VoLTE subscriber roams, voice is no longer a circuit-switched service handled by the visited MSC. It is a SIP session controlled by an IMS core, and…]]></description><link>https://esimcircle.hashnode.dev/inside-ims-registration-for-volte-roaming-s8hr-vs-local-breakout-p-cscf-discovery-and-sip-flows</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/inside-ims-registration-for-volte-roaming-s8hr-vs-local-breakout-p-cscf-discovery-and-sip-flows</guid><category><![CDATA[eSIM]]></category><category><![CDATA[Telecom]]></category><category><![CDATA[networking]]></category><category><![CDATA[mobile]]></category><category><![CDATA[5G]]></category><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Fri, 20 Nov 2026 05:39:05 GMT</pubDate><content:encoded><![CDATA[<p>When a VoLTE subscriber roams, voice is no longer a circuit-switched service handled by the visited MSC. It is a SIP session controlled by an IMS core, and the device must first complete an IMS registration before it can place or receive a single call. Where that registration terminates, and which network carries the SIP signalling and the RTP media, depends on the roaming architecture the two operators have agreed on.</p>
<p>This article walks through the components involved, the two main roaming architectures (S8 Home Routing and Local Breakout), how the device discovers its P-CSCF, the full registration message sequence, and the failure modes engineers most often meet when debugging VoLTE roaming.</p>
<h2>The IMS building blocks</h2>
<p>The IMS architecture is defined in 3GPP TS 23.228 (stage 2), and the SIP/SDP procedures in TS 24.229 (stage 3). The GSMA profile that constrains these specs for VoLTE devices and networks is IR.92, while IR.65 covers IMS roaming and interworking and IR.88 covers LTE roaming in general. The functions that matter for registration are:</p>
<ul>
<li><strong>P-CSCF (Proxy CSCF):</strong> the first SIP hop for the UE. It terminates the IPsec security associations toward the UE, enforces the route set, and talks to the PCRF over Rx so that voice bearers can be created.</li>
<li><strong>I-CSCF (Interrogating CSCF):</strong> the entry point into the home IMS domain. It queries the HSS to find (or select) the S-CSCF for a subscriber.</li>
<li><strong>S-CSCF (Serving CSCF):</strong> the registrar. It authenticates the user, downloads the service profile and applies initial Filter Criteria (iFC) to route requests to application servers.</li>
<li><strong>HSS:</strong> stores IMS subscription data and generates authentication vectors. The I-CSCF and S-CSCF use the Diameter Cx interface (TS 29.228 / TS 29.229).</li>
<li><strong>TAS / MMTel AS:</strong> the telephony application server that implements supplementary services. It receives a third-party REGISTER after the user registers.</li>
<li><strong>PCRF and PGW:</strong> on the EPS side, the IMS traffic runs over a dedicated PDN connection to the well-known IMS APN. SIP signalling typically uses a default bearer with QCI 5, and the voice media gets a dedicated bearer with QCI 1, created when the P-CSCF requests it via Rx.</li>
<li><strong>IBCF / TrGW:</strong> border functions used when signalling and media cross between operator IMS domains.</li>
</ul>
<p>The key observation for roaming is that the P-CSCF location follows the location of the PGW that anchors the IMS PDN connection. Everything else follows from that.</p>
<h2>Roaming architecture 1: S8 Home Routing (S8HR)</h2>
<p>In S8HR, the IMS APN is treated like any home-routed data APN. The visited network provides the eNodeB, MME and SGW; the PDN connection for the IMS APN is anchored on a PGW in the home network over the S8 interface, carried across the IPX.</p>
<p>Consequences:</p>
<ul>
<li>The P-CSCF is in the <strong>home</strong> network. The visited network does not need an IMS core for the roaming subscriber.</li>
<li>SIP signalling and RTP media are both tunnelled inside GTP-U from the visited SGW to the home PGW.</li>
<li>The visited network sees the voice traffic only as GTP-tunnelled bearers. QCI 1 and QCI 5 bearers still have to be supported in the VPLMN radio and SGW so that the voice bearer receives the correct QoS.</li>
<li>Deployment is simpler: the roaming agreement is closer to an LTE data roaming agreement with QCI support added.</li>
</ul>
<p>The open issues with S8HR are regulatory rather than technical: emergency calls and lawful interception in the visited country. Because the visited network has no IMS involvement in normal calls, emergency calls have to be handled locally, typically by the UE establishing an emergency PDN connection in the VPLMN, or by falling back to the circuit-switched domain where available. GSMA IR.65 describes these considerations, and later 3GPP releases added normative support for the S8HR architecture.</p>
<h2>Roaming architecture 2: Local Breakout (LBO)</h2>
<p>In VoLTE LBO, the IMS APN is broken out in the <strong>visited</strong> network. The PGW and P-CSCF are in the VPLMN, while the I-CSCF, S-CSCF, HSS and TAS stay in the HPLMN.</p>
<p>Consequences:</p>
<ul>
<li>The visited operator must run an IMS core with a P-CSCF that can serve inbound roamers, plus an IBCF to interconnect with the home IMS.</li>
<li>SIP signalling crosses the inter-operator boundary at the IMS layer (P-CSCF to I-CSCF via IBCFs), not at the GTP layer.</li>
<li>Media routing has more options. TS 23.228 defines the Roaming Architecture for Voice over IMS with Local Breakout (RAVEL), in which a Transit and Roaming Function (TRF) in the visited network can route media for a call locally rather than hairpinning it through the home network.</li>
<li>Emergency calls and lawful interception can be handled by the visited IMS, which is why some regulators prefer this model.</li>
</ul>
<h2>Discovering the P-CSCF</h2>
<p>Before sending any SIP, the UE needs the P-CSCF address. TS 24.229 allows several mechanisms; for VoLTE the dominant one is via the EPS session management procedure:</p>
<ol>
<li>The UE sends a PDN CONNECTIVITY REQUEST for the IMS APN (or the IMS PDN is requested during attach). In the Protocol Configuration Options (PCO), it includes "P-CSCF IPv4 Address Request" and/or "P-CSCF IPv6 Address Request".</li>
<li>The PGW (home PGW in S8HR, visited PGW in LBO) returns one or more P-CSCF addresses in the PCO of the response.</li>
<li>The UE stores the list and uses it for registration, falling back to the next address if the first one fails.</li>
</ol>
<p>Alternatives are DHCP-based discovery and pre-provisioned P-CSCF addresses (for example in an ISIM or device configuration), but PCO-based discovery is what IR.92 devices rely on. If the PCO response contains no P-CSCF address, the UE has nowhere to send REGISTER and VoLTE stays unavailable, even though the PDN connection itself succeeded.</p>
<h2>Identities used in the REGISTER</h2>
<p>The UE needs a private identity (IMPI), a public identity (IMPU) and a home network domain. If an ISIM application is present, these come from the ISIM. If not, TS 23.003 defines how they are derived from the IMSI on the USIM:</p>
<pre><code class="language-text">IMSI:            MCC=234, MNC=15, MSIN=0123456789  (example values)
Home domain:     ims.mnc015.mcc234.3gppnetwork.org
IMPI:            234150123456789@ims.mnc015.mcc234.3gppnetwork.org
Temporary IMPU:  sip:234150123456789@ims.mnc015.mcc234.3gppnetwork.org
</code></pre>
<p>Note that a two-digit MNC is zero-padded to three digits in the domain name. The temporary IMPU is only used for registration; the network returns the user's real public identities (for example a tel URI with the MSISDN) in the P-Associated-URI header of the 200 OK.</p>
<p>This detail matters for eSIM and multi-IMSI deployments: if the profile has no ISIM and the IMSI belongs to a different PLMN than the one hosting the IMS core, the derived home domain will point to the wrong network unless the operator has arranged routing for it.</p>
<h2>The registration sequence</h2>
<p>The following sequence shows an LBO registration. In S8HR the P-CSCF sits in the home network and the visited IBCF is not involved, but the SIP exchange is the same.</p>
<pre><code class="language-text">UE        P-CSCF(V)      IBCF        I-CSCF(H)     HSS        S-CSCF(H)      TAS
 |            |            |             |           |             |           |
 |--REGISTER-&gt;|            |             |           |             |           |
 |            |--REGISTER-&gt;|--REGISTER--&gt;|           |             |           |
 |            |            |             |--UAR-----&gt;|             |           |
 |            |            |             |&lt;--UAA-----|             |           |
 |            |            |             |--REGISTER--------------&gt;|           |
 |            |            |             |           |&lt;----MAR-----|           |
 |            |            |             |           |-----MAA----&gt;|           |
 |            |&lt;-----------401 Unauthorized (RAND, AUTN, CK, IK)---|           |
 |&lt;--401------|  (P-CSCF keeps CK/IK, sets up IPsec SAs)           |           |
 |                                                                 |           |
 |==REGISTER (over IPsec, RES-based response)=====================&gt;|           |
 |            |            |             |           |&lt;----SAR-----|           |
 |            |            |             |           |-----SAA----&gt;|           |
 |&lt;------------------------200 OK (Service-Route, P-Associated-URI)|           |
 |            |            |             |           |             |--3rd party|
 |            |            |             |           |             | REGISTER-&gt;|
 |--SUBSCRIBE (reg event)----------------------------------------&gt;|           |
</code></pre>
<p>Step by step:</p>
<ol>
<li><strong>Initial REGISTER.</strong> The UE sends REGISTER to the P-CSCF over UDP or TCP. It includes an Authorization header with the IMPI and an empty response, and a Security-Client header listing the IPsec parameters it supports (algorithms, SPIs and protected ports), as defined in TS 33.203 and RFC 3329.</li>
<li><strong>I-CSCF location.</strong> The P-CSCF resolves the home domain via DNS and forwards the request to the I-CSCF of the home network (through IBCFs in LBO). It adds a Path header so that terminating requests later come back through it, and a P-Visited-Network-ID header identifying the visited network.</li>
<li><strong>User authorization (UAR/UAA).</strong> The I-CSCF asks the HSS whether this user may register from this visited network and which S-CSCF to use. A roaming restriction at this point typically results in a 403 Forbidden back to the UE.</li>
<li><strong>Authentication vectors (MAR/MAA).</strong> The S-CSCF requests IMS AKA vectors from the HSS: RAND, AUTN, XRES, CK and IK.</li>
<li><strong>Challenge.</strong> The S-CSCF responds with 401 Unauthorized. The WWW-Authenticate header uses the AKAv1-MD5 algorithm, with the nonce carrying RAND and AUTN. CK and IK travel with the 401 toward the P-CSCF, which removes them before forwarding the challenge and uses them to establish IPsec ESP security associations with the UE. It returns its own parameters in Security-Server.</li>
<li><strong>Authenticated REGISTER.</strong> The UE runs AKA on the USIM or ISIM, verifying AUTN (which authenticates the network) and computing RES. It then sends a second REGISTER over the newly established IPsec SAs, with a digest response derived from RES and a Security-Verify header echoing the server parameters to protect against downgrade.</li>
<li><strong>Server assignment (SAR/SAA).</strong> After successful verification the S-CSCF registers the user in the HSS and downloads the user profile, including the iFCs.</li>
<li><strong>200 OK.</strong> The S-CSCF answers with 200 OK containing Service-Route (the route set for subsequent originating requests), P-Associated-URI (the registered public identities) and the registration expiry.</li>
<li><strong>Third-party registration.</strong> Based on iFCs, the S-CSCF sends a third-party REGISTER to the TAS so that the telephony services know the user is reachable.</li>
<li><strong>Registration event subscription.</strong> The UE, and normally the P-CSCF too, SUBSCRIBE to the "reg" event package (RFC 3680). This lets the network deregister the device or notify it of changes, for example during network-initiated re-authentication.</li>
</ol>
<p>The UE then periodically re-registers before expiry. Re-registration is a full AKA run unless the network chooses otherwise.</p>
<h2>Security details worth knowing</h2>
<ul>
<li><strong>Mutual authentication.</strong> IMS AKA reuses the UMTS/LTE AKA principle: the UE authenticates the network via AUTN and the sequence number check; the network authenticates the UE via RES.</li>
<li><strong>Sequence number resynchronization.</strong> If the SQN in AUTN is out of range, the UE responds with an AUTS parameter instead of RES. The S-CSCF sends it to the HSS in a new MAR, the HSS resynchronizes, and a fresh challenge follows. Repeated 401 responses in a trace are often this case, not a wrong key.</li>
<li><strong>IPsec between UE and P-CSCF only.</strong> The ESP SAs protect the first hop. Beyond the P-CSCF, protection relies on the operator network domain security, and on the IPX for inter-operator links.</li>
</ul>
<h2>Edge cases specific to roaming</h2>
<ul>
<li><strong>No IMS APN in the roaming agreement.</strong> The attach succeeds and data works, but the IMS PDN connection is rejected or never requested. The device falls back to CS voice (CSFB) if available, or has no voice in LTE-only networks.</li>
<li><strong>QCI 1 not supported or not allowed.</strong> Registration succeeds because SIP runs on QCI 5, but call setup fails when the dedicated bearer for voice cannot be established.</li>
<li><strong>Device or carrier configuration.</strong> Many devices enable VoLTE roaming only if the carrier configuration explicitly allows it for that profile. A device can register at home and refuse to try abroad, with no SIP sent at all.</li>
<li><strong>IPsec blocked or fragmented.</strong> Large SIP messages over UDP can exceed the path MTU. Fragmented ESP packets dropped on the path show up as timeouts on the second REGISTER. Switching to TCP for large messages, as TS 24.229 recommends, helps.</li>
<li><strong>Wrong home domain.</strong> Multi-IMSI and MVNO profiles without an ISIM may derive a home domain from an IMSI whose PLMN does not host the IMS core, leading to DNS failures at the P-CSCF.</li>
<li><strong>Emergency calls in S8HR.</strong> Emergency registration and calls require visited-network handling. Test this separately; normal registration success says nothing about emergency call routing.</li>
</ul>
<h2>Debugging tips</h2>
<ul>
<li><strong>Android.</strong> The hidden Phone Information menu (dialer code <code>*#*#4636#*#*</code> on many builds) shows IMS registration status and VoLTE provisioning flags. <code>adb logcat</code> with radio buffers (<code>adb logcat -b radio</code>) exposes ImsService and RIL events. Chipset vendor tools such as Qualcomm QXDM capture full NAS, PCO and SIP traces, but require engineering access.</li>
<li><strong>iOS.</strong> Field Test Mode (<code>*3001#12345#*</code>) shows limited serving-cell information. Detailed IMS traces generally require carrier or Apple diagnostic profiles, so network-side traces are usually more practical.</li>
<li><strong>Network side.</strong> Capture on the Gm interface at the P-CSCF and on Cx at the HSS. Correlate the IMPI from the REGISTER with the Diameter User-Name AVP.</li>
<li><strong>Read SIP status codes in context.</strong> 403 after UAR usually means a roaming or barring decision in the HSS; repeated 401 suggests SQN resync or key mismatch; 408 or 504 on the protected REGISTER points to transport or IPsec problems; 500-class responses from the S-CSCF often mean HSS or Diameter routing issues across the IPX.</li>
<li><strong>Check the PCO first.</strong> If there is no P-CSCF address in the PDN connectivity accept, none of the SIP analysis matters.</li>
</ul>
<h2>Summary</h2>
<p>VoLTE roaming registration is an IMS registration with one extra variable: where the IMS PDN connection breaks out. In S8HR the P-CSCF is in the home network and the visited network only carries GTP bearers with the right QCIs. In LBO the visited network runs the P-CSCF and an IBCF, and can optimize media with RAVEL. In both cases the core sequence is the same: P-CSCF discovery via PCO, REGISTER, UAR, MAR, a 401 challenge that bootstraps IPsec, a protected REGISTER, SAR, 200 OK, third-party registration and a reg-event subscription. Most field failures trace back to the edges of this flow: missing PCO entries, roaming restrictions in the HSS, unsupported bearers, or transport issues on the IPsec path.</p>
<h2>Further reading</h2>
<ul>
<li><a href="https://esimcircle.hashnode.dev/home-routing-vs-local-breakout-how-roaming-data-traffic-is-routed">Home Routing vs Local Breakout: How Roaming Data Traffic Is Routed</a></li>
<li><a href="https://www.3gpp.org/DynaReport/23228.htm">3GPP TS 23.228: IP Multimedia Subsystem (IMS); Stage 2</a></li>
<li><a href="https://www.gsma.com/newsroom/resources/ir-92-ims-profile-for-voice-and-sms/">GSMA IR.92: IMS Profile for Voice and SMS</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How Steering of Roaming Decides Which Network Your Phone Joins Abroad]]></title><description><![CDATA[Photo: Przemek Leśniewski via Pexels When a phone lands in a foreign country and comes out of airplane mode, it usually sees several mobile networks at…]]></description><link>https://esimcircle.hashnode.dev/how-steering-of-roaming-decides-which-network-your-phone-joins-abroad</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/how-steering-of-roaming-decides-which-network-your-phone-joins-abroad</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 19 Nov 2026 04:15:11 GMT</pubDate><content:encoded><![CDATA[<img src="https://images.pexels.com/photos/36359722/pexels-photo-36359722.jpeg?auto=compress&amp;cs=tinysrgb&amp;w=1260" alt="Tall cellular tower against a clear blue sky" style="display:block;margin:0 auto" />

<p><em>Photo: Przemek Leśniewski via Pexels</em></p>
<p>When a phone lands in a foreign country and comes out of airplane mode, it usually sees several mobile networks at once. Travelers often assume the phone simply picks the strongest signal. In reality, the choice is shaped by lists stored on the SIM or eSIM profile, by rules defined in 3GPP specifications, and by a commercial mechanism called <strong>steering of roaming</strong> (SoR). This article explains how those pieces fit together and what they mean for someone landing in, say, Paris with a travel eSIM.</p>
<h2>What steering of roaming is</h2>
<p>Steering of roaming is the set of techniques a home operator uses to influence which visited network its subscribers attach to while abroad. Home operators have wholesale agreements with partner networks in each country, and those agreements usually differ in price, quality and coverage. The home operator therefore prefers some partners over others, and SoR is how that preference is enforced.</p>
<p>It is important to separate two ideas: <em>which networks a subscriber is allowed to use</em> (determined by roaming agreements) and <em>which allowed network the device ends up on</em> (determined by selection logic and steering). A network can be technically permitted and still be deprioritized.</p>
<h2>The building blocks stored on the SIM profile</h2>
<p>PLMN selection is defined in 3GPP TS 23.122. A PLMN is identified by its MCC and MNC, and the SIM or eSIM profile carries several lists that the device consults in automatic mode:</p>
<ul>
<li><strong>HPLMN / EHPLMN:</strong> the home network and any equivalent home networks.</li>
<li><strong>User controlled PLMN selector:</strong> preferences set by the user, rarely used today.</li>
<li><strong>Operator controlled PLMN selector with access technology (OPLMNwACT):</strong> the home operator's ranked list of preferred partners per country, optionally per radio technology.</li>
<li><strong>Forbidden PLMN list:</strong> networks that rejected registration with a permanent cause and should not be retried.</li>
</ul>
<p>In automatic mode, the device first tries the home network, then the user list, then the operator list, then other networks with acceptable signal quality, roughly in that order. The operator list is the main "soft" steering tool because it can be updated over the air.</p>
<h2>Network-side steering: rejecting registrations</h2>
<p>Lists on the SIM are not always up to date, so many operators also steer from the network side. When the device tries to register on a visited network, that network sends an update location request back to the home core (the HSS in LTE or the UDM in 5G). A steering platform in the home network can intercept the request and answer with a reject, causing the device to try the next candidate.</p>
<p>Devices only accept a limited number of such rejects before they settle on a network anyway, which is why steering is designed to give up after a few attempts rather than leave a subscriber without service. The side effect is that the first minutes after landing can involve several silent registration attempts, a short delay before data works, and occasionally a switch to a different network a little later.</p>
<h2>Steering in 5G</h2>
<p>5G standalone systems introduced a cleaner approach. During registration the UDM can deliver an updated list of preferred PLMN and access technology combinations to the device in a protected container, which the device stores and uses for subsequent selection. This reduces the reliance on reject-based steering, although many travelers still roam over LTE or 5G non-standalone, where the older mechanisms remain common.</p>
<h2>Periodic searches for a better network</h2>
<p>Once registered on a visited network that is not top of the preference list, the device periodically searches for a higher priority network. The interval is configurable by the operator and stored on the profile. This is why a phone that attached to a less preferred partner at the airport may quietly move to another network after an hour in the city.</p>
<h2>What travelers actually notice</h2>
<ul>
<li><strong>A short delay on arrival:</strong> data may take a minute or two longer to start while the device works through rejected attempts.</li>
<li><strong>A network name that changes:</strong> the status bar can show one operator at the airport and another later on.</li>
<li><strong>Coverage differences outside cities:</strong> if the preferred partner has weaker rural coverage, the phone may stay on it even where another network is stronger, unless the profile allows multiple partners.</li>
<li><strong>Manual selection limits:</strong> choosing a network manually only works if that network is permitted for the profile; otherwise it will be rejected.</li>
</ul>
<h2>Where travel eSIMs fit</h2>
<p>Most travel eSIMs are roaming profiles: the profile belongs to an issuing operator in one country and uses partner networks in the destination. All the mechanisms above therefore still apply, but the preference list belongs to the eSIM's issuing operator, not to your home carrier. Good plans publish which local networks are supported in each country, and some allow more than one partner, which helps when one network is weak in a specific area. Exact partner lists and speeds vary by provider and change over time, so check the plan details rather than assuming.</p>
<h2>A short troubleshooting checklist</h2>
<ol>
<li>Confirm data roaming is enabled for the eSIM line and that the line is selected for mobile data.</li>
<li>Toggle airplane mode once and give the device a few minutes to complete registration.</li>
<li>If you are stuck on "No service", switch network selection to manual, wait for the list, and pick one of the networks your plan lists as supported, then switch back to automatic later.</li>
<li>Check that the APN matches the provider's instructions if registration succeeds but data does not.</li>
<li>Contact the provider with the network name shown and the time of the issue; that information maps directly to registration logs.</li>
</ol>
<h2>Staying connected in France</h2>
<p>For a trip through France, a prepaid travel eSIM avoids the uncertainty of home carrier roaming charges while still using local partner networks. eSIMCircle is one option, with plans listed on its <a href="https://esimcircle.com/esims/france-esim/">France eSIM page</a>; whichever provider you choose, compare the supported networks, validity and fair-use terms before you travel.</p>
<h2>Related reading</h2>
<ul>
<li><a href="https://esimcircle.vercel.app/gl/france-esim/france-esim-guide-for-first-time-visitors.html">France eSIM Guide for First-Time Visitors</a></li>
<li><a href="https://esimcircle.github.io/eSIMCircle/gl/france-esim/france-arrival-connectivity-guide-for-short-trips-and-long-stays.html">France Arrival Connectivity Guide for Short Trips and Long Stays</a></li>
<li><a href="https://esimcircle.travelesim.workers.dev/gl/france-esim/france-esim-cost-guide-for-avoiding-roaming-fees">France eSIM Cost Guide for Avoiding Roaming Fees</a></li>
<li><a href="https://esimcircleglobal.mataroa.blog/blog/france-long-stay-travel-tips/">France Long-Stay Travel Tips</a></li>
<li><a href="http://network.hu/esimcircleglobal/blog/global-blogja/best-compact-itinerary-ideas-for-paris">Best Compact Itinerary Ideas for Paris</a></li>
<li><a href="https://rentry.co/france-emergency-numbers-useful-contacts">France Emergency Numbers and Useful Contacts</a></li>
</ul>
<h2>Follow eSIMCircle</h2>
<p>More travel and eSIM tips from eSIMCircle: <a href="https://www.facebook.com/esimcircle">Facebook</a> · <a href="https://www.instagram.com/esim.circle/">Instagram</a> · <a href="https://www.tiktok.com/@esim.circle">TikTok</a> · <a href="https://www.threads.com/@esim.circle">Threads</a> · <a href="https://x.com/esim_circle">X</a> · <a href="https://www.linkedin.com/company/esimcircle/">LinkedIn</a> · <a href="https://www.youtube.com/watch?v=99nC0dtXbmI">YouTube</a> · <a href="https://music.amazon.com/podcasts/0f18d24d-ca76-4477-9a19-203533084777/">Amazon Music</a> · <a href="https://esimcircle.gumroad.com/">Gumroad</a></p>
]]></content:encoded></item><item><title><![CDATA[Home Routing vs Local Breakout: How Roaming Data Traffic Is Routed]]></title><description><![CDATA[When a phone roams abroad and opens a data session, the visited network gives it radio access, but the traffic does not necessarily leave the internet in…]]></description><link>https://esimcircle.hashnode.dev/home-routing-vs-local-breakout-how-roaming-data-traffic-is-routed</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/home-routing-vs-local-breakout-how-roaming-data-traffic-is-routed</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Wed, 18 Nov 2026 12:36:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/68d80c5e1e46b2003c547077/ab1a0487-53c5-4586-89b0-bef8cf80ad44.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When a phone roams abroad and opens a data session, the visited network gives it radio access, but the traffic does not necessarily leave the internet in the country where the user is standing. Where that traffic exits depends on the roaming architecture the operators have agreed on. The two main models are home routing and local breakout, and the choice between them affects latency, IP geolocation, policy control and how roaming is billed.</p>
<p>This article walks through both models in LTE and 5G, explains why most roaming data is still home-routed, and shows how this affects travel eSIM users.</p>
<h2>The basic roaming setup</h2>
<p>In any roaming scenario there are two operators:</p>
<ul>
<li><strong>HPLMN (home network):</strong> the operator that issued the subscriber's profile and holds the subscription data in its HSS or UDM.</li>
<li><strong>VPLMN (visited network):</strong> the local operator whose radio network and core the device attaches to abroad.</li>
</ul>
<p>Authentication and authorization still rely on the home network. The visited core contacts the home HSS or UDM to authenticate the subscriber and fetch the subscription profile. What changes between roaming models is where the user plane, the actual data packets, is anchored.</p>
<h2>Home routing in LTE</h2>
<p>In LTE home-routed roaming, the device attaches to the visited network's eNodeB, MME and Serving Gateway (SGW). The data session is anchored at the PDN Gateway (PGW) in the home network. The visited SGW and home PGW are connected over the S8 interface, and user traffic is carried inside GTP tunnels across an inter-operator backbone such as an IPX network.</p>
<p>The path for a packet looks like this:</p>
<ol>
<li>Device to visited eNodeB.</li>
<li>Visited eNodeB to visited SGW.</li>
<li>Visited SGW over S8 to home PGW, often across countries.</li>
<li>Home PGW out to the internet.</li>
</ol>
<p>Because the PGW assigns the IP address and applies policy, the device appears on the internet with an IP from the home operator's range. A user in Tokyo with a home-routed profile from a European operator will often see websites treat them as if they were in Europe.</p>
<h2>Local breakout in LTE</h2>
<p>With local breakout (LBO), the PGW is in the visited network. The device's session is anchored locally, and traffic exits to the internet in the visited country. The home network still authenticates the user and may still apply some policy through roaming interfaces, but the data path is much shorter.</p>
<p>Local breakout reduces latency and transit costs, and it lets traffic reach local content delivery networks directly. In practice it is less common for general internet traffic, because it requires closer commercial and technical agreements, and it makes it harder for the home operator to apply its own charging, policy and lawful interception functions.</p>
<h2>Home routing and local breakout in 5G</h2>
<p>The 5G core keeps the same two options with new network functions:</p>
<ul>
<li><strong>Home-routed:</strong> the visited network runs a V-SMF and V-UPF, while the home network runs the H-SMF and H-UPF that anchor the PDU session. User plane traffic travels between the two UPFs over the N9 interface.</li>
<li><strong>Local breakout:</strong> the SMF and UPF that anchor the PDU session sit in the visited network, and traffic exits locally.</li>
</ul>
<p>Signaling between the two 5G cores passes through Security Edge Protection Proxies (SEPP) on each side, which protect the service-based interfaces that cross operator boundaries.</p>
<h2>Trade-offs at a glance</h2>
<table>
<thead>
<tr>
<th>Aspect</th>
<th>Home routing</th>
<th>Local breakout</th>
</tr>
</thead>
<tbody><tr>
<td>Latency</td>
<td>Higher, because traffic travels to the home country first</td>
<td>Lower, traffic exits locally</td>
</tr>
<tr>
<td>Public IP location</td>
<td>Usually home country</td>
<td>Usually visited country</td>
</tr>
<tr>
<td>Policy and charging</td>
<td>Fully controlled by home operator</td>
<td>Shared or more complex</td>
</tr>
<tr>
<td>Inter-operator agreements</td>
<td>Widely available</td>
<td>Requires specific agreements</td>
</tr>
<tr>
<td>Transit cost</td>
<td>Higher backbone usage</td>
<td>Lower backbone usage</td>
</tr>
</tbody></table>
<h2>Why travel eSIM users notice this</h2>
<p>Many travel eSIM plans use profiles issued by an operator in one country that roam onto partner networks in many others. With home routing, the public IP address and the apparent location of the device can be in the profile's home country rather than the destination. This explains several common observations from travelers:</p>
<ul>
<li>Websites or apps show content or language settings for another country.</li>
<li>Speed tests show higher latency to local servers than a local SIM would.</li>
<li>Some region-locked services behave differently than expected.</li>
</ul>
<p>None of this means the connection is broken. It is a direct result of where the session is anchored. Some providers use regional breakout points or local partners to reduce latency, but the exact setup varies by plan and network.</p>
<h2>Practical implications for system design</h2>
<ul>
<li><strong>Do not rely on IP geolocation</strong> to determine where a roaming user is. Use device location or explicit user input instead.</li>
<li><strong>Expect higher round-trip times</strong> for home-routed users when setting timeouts in mobile apps.</li>
<li><strong>Design APIs to be tolerant of IP changes</strong>, since the egress point can change when a device moves between networks or plans.</li>
<li><strong>Monitor by network, not only by country</strong>, when troubleshooting roaming performance.</li>
</ul>
<h2>Summary</h2>
<p>Home routing anchors the data session in the home network and sends traffic back across an inter-operator backbone, which keeps control with the home operator but adds latency and changes the apparent location of the user. Local breakout anchors the session in the visited network for a shorter path and local egress, but requires closer cooperation between operators. Understanding which model a plan uses explains a lot about the roaming experience, from speed test results to why a website thinks you are in another country.</p>
<p>For travelers who want to understand their options before a trip, <a href="https://esimcircle.com/">eSIMCircle</a> publishes plan details and offers round-the-clock support for setup and connection questions.</p>
<p><em>Cover photo: ProtSilver Chen via Pexels</em></p>
<h2>Related reading</h2>
<ul>
<li><a href="https://dev.to/esim_circle/best-travel-apps-for-vietnam-106i">Best Travel Apps for Vietnam</a></li>
<li><a href="https://esimcircle.exblog.jp/35284047/">Best eSIM for Japan in 2026: Travel Data Guide</a></li>
<li><a href="http://network.hu/esimcircleglobal/blog/global-blogja/flexible-travel-e-sim-plans-for-200-destinations-e-sim-circle">Flexible Travel eSIM Plans for 200+ Destinations</a></li>
<li><a href="https://esimcircle.tumblr.com/post/803990100908359680/esim-errors">eSIM Errors: Common Problems and Fixes</a></li>
<li><a href="https://esimcircle.tumblr.com/post/804254683545862144/esim-for-iphone">eSIM for iPhone</a></li>
<li><a href="https://esimcircle.github.io/eSIMCircle/gl/thailand-esim/thailand-esim-cost-guide-for-avoiding-roaming-fees.html">Thailand eSIM Cost Guide for Avoiding Roaming Fees</a></li>
</ul>
<h2>Follow eSIMCircle</h2>
<p>More travel and eSIM tips from eSIMCircle: <a href="https://www.facebook.com/esimcircle">Facebook</a> · <a href="https://www.instagram.com/esim.circle/">Instagram</a> · <a href="https://www.tiktok.com/@esim.circle">TikTok</a> · <a href="https://www.threads.com/@esim.circle">Threads</a> · <a href="https://x.com/esim_circle">X (Twitter)</a> · <a href="https://www.linkedin.com/company/esimcircle/">LinkedIn</a> · <a href="https://www.youtube.com/watch?v=99nC0dtXbmI">YouTube</a> · <a href="https://music.amazon.com/podcasts/0f18d24d-ca76-4477-9a19-203533084777/">Amazon Music</a> · <a href="https://esimcircle.gumroad.com/">Gumroad</a></p>
]]></content:encoded></item><item><title><![CDATA[How eSIM Changes Subscriber Provisioning Architecture]]></title><description><![CDATA[Subscriber provisioning used to be a back-office batch process with a physical endpoint. You prepared a card, shipped it, and the subscriber record in the…]]></description><link>https://esimcircle.hashnode.dev/how-esim-changes-subscriber-provisioning-architecture</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/how-esim-changes-subscriber-provisioning-architecture</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:53:36 GMT</pubDate><content:encoded><![CDATA[<p>Subscriber provisioning used to be a back-office batch process with a physical endpoint. You prepared a card, shipped it, and the subscriber record in the core network was loaded before or alongside it. eSIM keeps the core network side largely familiar, but it moves the point where credentials reach the device into a live, interactive, internet-facing flow. That change reshapes the architecture around it.</p>
<h2>The classic provisioning picture</h2>
<p>In a traditional setup, a few systems cooperate:</p>
<pre><code class="language-text">Order/BSS  -&gt;  SIM vendor / personalization  -&gt;  physical card shipped
    |
    +--&gt;  subscriber data loaded into HSS/UDM (IMSI, key material, services)
</code></pre>
<p>The subscriber data in the core (HSS in LTE, UDM and related functions in 5G) and the secret on the card must match. Matching happens by loading the same key material into both places, ahead of use.</p>
<h2>What the eSIM architecture adds</h2>
<p>eSIM introduces new elements between the operator and the device:</p>
<pre><code class="language-text">Operator BSS/OSS  -&gt;  Profile preparation  -&gt;  SM-DP+  &lt;-&gt;  LPA on device  -&gt;  eUICC
                                                |
                                         SM-DS (optional discovery)
</code></pre>
<p>The SM-DP+ stores prepared profiles and delivers them securely. The LPA on the device drives the download and talks to the user interface. The SM-DS can help a device discover that a profile is waiting for it. The eUICC verifies identities and decrypts the package.</p>
<p>The core network side, with its HSS or UDM, still needs the subscriber record for each profile. What changes is the timing: the profile is created and the matching core data must exist before the device downloads and attaches, but the physical object is replaced with a downloadable package.</p>
<h2>Consequences for the architecture</h2>
<p>Provisioning becomes event-driven. Instead of a one-time batch load, you run an ongoing process of reserving, preparing, releasing and confirming profiles. State handling, idempotency and reconciliation become first-class concerns, as explored elsewhere in this series.</p>
<p>The edge is now the internet. The SM-DP+ is reached by consumer devices on arbitrary networks, so availability, rate limiting, TLS configuration and abuse handling matter in a way that a back-office SIM vendor interface did not.</p>
<p>Orders and profiles decouple. A customer can buy first and install later. A platform has to represent that gap, with a reservation, an issued activation, a download and a confirmation as separate steps.</p>
<p>Core data must stay in sync. Preparing a profile on the SM-DP+ and creating the subscriber record in the core are two operations. If one succeeds and the other fails, you end up with a profile nobody can authenticate with, or a core record with no profile. A reconciliation job comparing both sides is a practical safeguard.</p>
<h2>Interfaces you will meet</h2>
<p>Providers integrate with an SM-DP+ through operator-facing and platform-specific APIs, and with their BSS, billing and customer care systems. The device-facing protocol between LPA and SM-DP+ is defined in the GSMA specifications, but a provider building on a platform usually sees a higher-level API. Read the documentation of whichever platform you integrate with, because details such as notification formats and retry behaviour differ.</p>
<h2>Security shifts</h2>
<p>The secrets still matter as much as before, but where they sit changes. Activation codes, QR codes and confirmation codes become credentials that travel through emails, web pages and customer chats. They need access control, short validity and careful logging, as discussed in the security posts of this series. Audit trails of who requested and received which profile become more valuable.</p>
<h2>Observability and operations</h2>
<p>Because the flow is interactive, you can measure it: time from order to download, download failure rate, share of profiles never installed, time to first attach. These metrics turn provisioning from an invisible batch process into something you can monitor and tune.</p>
<h2>Summary</h2>
<p>eSIM does not rewrite the mobile core, but it changes how subscribers get provisioned. A batch-and-ship process becomes a networked, stateful, event-driven service with an internet-facing edge. Treat it like any distributed system: explicit states, idempotent operations, reconciliation, and good telemetry.</p>
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[Physical SIM vs eSIM from a Systems Architecture Perspective]]></title><description><![CDATA[A physical SIM and an eSIM can carry the same subscriber identity and give the same service. Architecturally they are quite different, because the thing…]]></description><link>https://esimcircle.hashnode.dev/physical-sim-vs-esim-from-a-systems-architecture-perspective</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/physical-sim-vs-esim-from-a-systems-architecture-perspective</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:52:03 GMT</pubDate><content:encoded><![CDATA[<p>A physical SIM and an eSIM can carry the same subscriber identity and give the same service. Architecturally they are quite different, because the thing that changes is where and when the credentials get into the secure element. This post compares the two from the systems side: manufacturing, logistics, provisioning, and failure modes.</p>
<h2>The same job, different lifecycle</h2>
<p>A SIM card is a secure element running a small operating system, holding an IMSI, an authentication key and related data. Both formats do that job. The difference is the lifecycle.</p>
<pre><code class="language-text">Physical SIM:  personalize at factory -&gt; ship card -&gt; insert -&gt; use
eSIM (eUICC):  manufacture blank eUICC -&gt; ship device -&gt; download profile -&gt; enable -&gt; use
</code></pre>
<p>For a physical SIM, personalization happens before the card leaves the factory. The operator generates keys, writes them to the card, and ships it. For an eSIM, the eUICC is manufactured with a platform and a certificate-based trust setup, and the operator's credentials arrive later, over the network, as a profile.</p>
<h2>Where the secrets are born</h2>
<p>With physical SIMs, the key material is produced in a personalization process and handed over in files to the card vendor, often under strict physical and procedural controls. Those key files are a long-lived liability: they exist in transit and at rest between organizations.</p>
<p>With eSIM, the operator's profile is prepared by a profile preparation service and held by the SM-DP+. The package is encrypted for a specific eUICC at download time, using keys established during the session. The data leaves the SM-DP+ only in a bound form that only the target eUICC can open. There are still sensitive files and processes, but the distribution step is automated and tied to the device.</p>
<h2>Logistics and inventory</h2>
<p>A physical SIM is a stock item: print runs, packaging, shipping, customs, courier delays and lost parcels. Inventory is counted in boxes.</p>
<p>An eSIM profile is a database record on the operator or provider side. Inventory is counted in rows, and "shipping" is a network download. That makes the problems different. You avoid parcels, but you inherit software problems such as double assignment, reservation expiry and idempotent delivery, as covered in the earlier posts in this series.</p>
<h2>Provisioning flow compared</h2>
<pre><code class="language-text">Physical:   order -&gt; pick card -&gt; ship -&gt; customer inserts -&gt; network attach
eSIM:       order -&gt; reserve profile -&gt; issue activation data -&gt; device downloads -&gt; enable -&gt; network attach
</code></pre>
<p>The network attach at the end is the same in both cases, with SIM authentication and registration as usual. Everything before it is where the architecture differs. The eSIM path adds more services (reservation, SM-DP+ interaction, notifications) and removes the physical chain.</p>
<h2>Failure modes</h2>
<p>Physical SIM failures are mostly physical or logistical: a card is damaged, mis-shipped, put in the wrong slot, or the tray is lost. Fixes involve replacing hardware.</p>
<p>eSIM failures are mostly software and connectivity: a download fails because the device is offline, the activation data is invalid or already used, the profile is not compatible with the device, or the eUICC lacks space. Fixes involve retrying, re-issuing or reassigning a profile, which is why lifecycle state handling matters so much.</p>
<h2>Identity and swapping</h2>
<p>Moving a physical SIM between phones moves the subscription with it, which is both convenient and the basis of SIM-swap physical theft. An eSIM is bound to its eUICC, identified by an EID. Moving a profile to another device generally means a new download or a transfer procedure defined by the operator and device, with its own authentication steps. This changes the fraud and support story, though it does not remove risk.</p>
<h2>Operational impact on a provider</h2>
<p>Moving from physical to eSIM shifts effort from warehouse and shipping operations to software reliability and observability. You need good monitoring of the provisioning pipeline, clear error reporting from device flows, and support tooling that can see profile state. The cost of a mistake changes too: a software bug can affect many customers at once, while a shipping mistake affects the parcels involved.</p>
<h2>Summary</h2>
<p>The authentication and network side are the same for both formats. The differences sit in how credentials are generated, distributed and bound to the secure element, and in the lifecycle around that. Physical SIM is a logistics problem. eSIM is a distributed-systems problem.</p>
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[What Happens When an eSIM Profile Is Enabled or Disabled]]></title><description><![CDATA["Enabled" and "disabled" are the two states that people picture when they think of switching an eSIM on and off, but under the hood they are specific…]]></description><link>https://esimcircle.hashnode.dev/what-happens-when-an-esim-profile-is-enabled-or-disabled</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/what-happens-when-an-esim-profile-is-enabled-or-disabled</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:50:26 GMT</pubDate><content:encoded><![CDATA[<p>"Enabled" and "disabled" are the two states that people picture when they think of switching an eSIM on and off, but under the hood they are specific profile states on the eUICC with specific rules. Backend engineers need to understand them because they decide what the device can do and what the network sees. This post covers the on-card model and what it means for the systems around it.</p>
<h2>Profiles live on the eUICC, in one of two states</h2>
<p>An eUICC can hold several profiles. Each installed profile is either disabled or enabled. A disabled profile is present in storage but inactive. An enabled profile is the one the modem uses for network access. The details differ between implementations, but the common consumer design keeps a single enabled profile at a time. Some devices and eUICCs support more than one active profile, so check the target hardware instead of assuming.</p>
<pre><code class="language-text"> Installed (disabled)  &lt;-- disable --  Enabled
        |                                 ^
        +-------------- enable -----------+
</code></pre>
<p>Deleting a profile is a separate operation and is only allowed from the disabled state in the usual flow. That is a safety rule: you cannot remove the profile you are currently attached with.</p>
<h2>What enabling actually does</h2>
<p>When the LPA asks the eUICC to enable a profile, the eUICC makes that profile's file system and applications the active ones, and the previously enabled profile is disabled. The modem then restarts its connection logic with the new subscription data. In practice this means the device performs a fresh network attach with the new identity.</p>
<p>From the network's point of view, this looks like a new subscriber arriving. The IMSI is different, the authentication keys are different, and the device registers again. Nothing about the old session carries over.</p>
<h2>Where the backend gets involved</h2>
<p>The backend rarely sees the enable event directly. It usually learns about it indirectly:</p>
<pre><code class="language-text">device -&gt; eUICC:     enable profile
eUICC  -&gt; operator:  (new attach with the new IMSI)
core   -&gt; OSS/BSS:   first registration, location update, first data session
</code></pre>
<p>A first successful attach from a newly installed profile is therefore a useful proxy signal that the profile was enabled and works. It is not a guarantee of an explicit enable notification, so design your model around network-side evidence as well as device-reported events.</p>
<h2>Modeling it in a backend</h2>
<p>A simple, honest model tracks what you know and where it came from:</p>
<pre><code class="language-sql">ALTER TABLE profiles
  ADD COLUMN last_seen_enabled_at timestamptz,
  ADD COLUMN last_attach_at       timestamptz,
  ADD COLUMN enabled_source       text;   -- 'device_report' | 'network_attach'
</code></pre>
<p>Avoid a boolean such as <code>is_enabled</code> that implies certainty. Disabling can happen at any time on the device, such as when the user switches to another profile, and you may not be told. Store timestamps and sources, and derive a status when you display it.</p>
<h2>Disabling and the user experience</h2>
<p>A traveler may disable a profile to switch back to a home plan, or keep it disabled until arrival. The profile and its data allowance remain bound to that eUICC. From a billing and entitlement view, disabled does not mean cancelled. Make sure your usage logic and expiry rules do not confuse the two. Validity periods generally run on the plan's own rules, not on the device state.</p>
<h2>Edge cases worth handling</h2>
<p>Enable failures: a profile can fail to enable because of a connectivity problem, a device restriction or a profile policy rule. Record failure events and keep the profile in its prior state in your model until you have evidence otherwise.</p>
<p>Profile policy rules: a profile may carry rules, for example that it cannot be disabled or deleted. Operators use this for managed deployments. Do not assume every profile can be switched freely.</p>
<p>Multiple profiles: if a customer installs profiles from several providers, your system sees only its own. Do not infer that your profile is the active one from the absence of other data.</p>
<h2>Testing</h2>
<p>If you build tooling around this flow, test it on real devices where you can, because emulators rarely reproduce the modem's re-attach behaviour. Log the time between the enable action and the first network registration, which is a good health metric for a provisioning service.</p>
<h2>Summary</h2>
<p>Enabled and disabled are eUICC states with clear rules. The backend usually infers them from device reports and network attach events, so store timestamps and sources, not a single boolean, and keep entitlement logic independent from the on-card state.</p>
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[How eSIM Download Confirmation Can Be Modeled in Backend Systems]]></title><description><![CDATA[A common mistake in provisioning systems is treating "the API returned a profile" as the same thing as "the customer has an eSIM". Those are separate…]]></description><link>https://esimcircle.hashnode.dev/how-esim-download-confirmation-can-be-modeled-in-backend-systems</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/how-esim-download-confirmation-can-be-modeled-in-backend-systems</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:48:51 GMT</pubDate><content:encoded><![CDATA[<p>A common mistake in provisioning systems is treating "the API returned a profile" as the same thing as "the customer has an eSIM". Those are separate facts, and the gap between them is where support tickets live. Download confirmation is the signal that closes that gap. This post sketches how to model it so the backend knows what actually happened on the device.</p>
<h2>Why confirmation exists at all</h2>
<p>In the GSMA consumer flow, the LPA on the phone talks to the SM-DP+, downloads a bound profile package and installs it on the eUICC. Afterwards the SM-DP+ learns the outcome, and it can notify the operator side, which in turn can notify you. Your backend never sees the device. It only sees messages about the device, and those can be late, duplicated or missing. So the model has to be built around uncertainty.</p>
<h2>Separate three facts</h2>
<p>Keep these as distinct fields or states instead of one "installed" flag:</p>
<pre><code class="language-text">issued      - we handed out an activation code or profile reference
downloaded  - the SM-DP+ or operator reports the package was delivered
confirmed   - a final success report arrived (installation result)
</code></pre>
<p>Each one moves forward on its own evidence. A profile can be downloaded and never confirmed, for example if the phone lost power right after delivery. Collapsing the three hides exactly the cases you need to investigate.</p>
<h2>Store confirmations as events</h2>
<p>Treat every inbound message as an immutable event and derive state from them:</p>
<pre><code class="language-sql">CREATE TABLE profile_events (
  id            bigserial PRIMARY KEY,
  profile_id    uuid        NOT NULL,
  event_type    text        NOT NULL,   -- DOWNLOAD_REPORTED, INSTALL_SUCCEEDED, INSTALL_FAILED
  external_id   text        NOT NULL,   -- id from the upstream notification
  payload       jsonb       NOT NULL,
  received_at   timestamptz NOT NULL DEFAULT now(),
  UNIQUE (profile_id, external_id)
);
</code></pre>
<p>The unique constraint on <code>external_id</code> makes duplicate deliveries harmless. If the upstream retries a notification, the insert conflicts and you move on.</p>
<h2>Fold events into state with a small reducer</h2>
<pre><code class="language-python">ORDER = {"ISSUED": 0, "DOWNLOADED": 1, "INSTALLED": 2}

def apply(state: str, event_type: str) -&gt; str:
    target = {
        "DOWNLOAD_REPORTED": "DOWNLOADED",
        "INSTALL_SUCCEEDED": "INSTALLED",
    }.get(event_type)
    if target is None:
        return state            # failures are handled separately
    return target if ORDER[target] &gt; ORDER[state] else state
</code></pre>
<p>Because the reducer only moves forward, an out-of-order message, such as a download report arriving after the install success, cannot push the profile backwards. That is a cheap defence against reordering.</p>
<h2>Handle failure and silence differently</h2>
<p>A failure event is explicit: record it, move the profile to a failed state and decide on retry. Silence is harder. If a profile has been issued for a long time with no download event, you cannot tell whether the customer has not tried yet or something broke. Model it as a time-based check, not as an assumption:</p>
<pre><code class="language-sql">SELECT id
FROM   profiles
WHERE  state = 'ISSUED'
  AND  issued_at &lt; now() - interval '48 hours';
</code></pre>
<p>Use that list to drive reminders or support outreach, not to automatically reclaim the profile. A profile that may already be installed on a device must never be handed to someone else.</p>
<h2>Reconcile against the source of truth</h2>
<p>Notifications are a convenience. The operator or SM-DP+ usually has a status you can query. Run a periodic reconciliation that compares your state with theirs for profiles in ambiguous states, and record any disagreement as an event. This turns a lost webhook into a delayed update instead of a permanent mismatch.</p>
<h2>Expose the model to the rest of the system</h2>
<p>Customer support tools and storefront pages should read the derived state, and show wording that matches the evidence, for example "download reported" instead of "installed" when only the first fact is known. Accurate labels reduce confusion on both sides.</p>
<h2>Summary</h2>
<p>Model issued, downloaded and confirmed as separate facts, store inbound messages as de-duplicated events, fold them forward-only, treat silence with time-based checks, and reconcile against the upstream source regularly.</p>
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[Designing a Profile Reservation System with Expiration]]></title><description><![CDATA[A reservation is a promise with a deadline. When a customer starts checkout, you hold a profile for them so nobody else can take it. If they never pay, the…]]></description><link>https://esimcircle.hashnode.dev/designing-a-profile-reservation-system-with-expiration</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/designing-a-profile-reservation-system-with-expiration</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:47:21 GMT</pubDate><content:encoded><![CDATA[<p>A reservation is a promise with a deadline. When a customer starts checkout, you hold a profile for them so nobody else can take it. If they never pay, the hold has to end and the profile has to return to stock. Get the expiry wrong in one direction and you sell profiles twice. Get it wrong in the other and stock quietly disappears. Here is a design that avoids both.</p>
<h2>Model the hold as a row with an expiry</h2>
<p>Keep reservations in their own table instead of overloading the profile status:</p>
<pre><code class="language-sql">CREATE TABLE reservations (
  id          uuid PRIMARY KEY,
  profile_id  uuid        NOT NULL REFERENCES profiles(id),
  order_id    uuid        NOT NULL,
  status      text        NOT NULL DEFAULT 'ACTIVE',
  expires_at  timestamptz NOT NULL,
  created_at  timestamptz NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX one_active_reservation_per_profile
ON reservations (profile_id)
WHERE status = 'ACTIVE';
</code></pre>
<p>The partial unique index guarantees that a profile has at most one active hold, even if two workers race. Expiry then becomes a status change, not a delete, so you keep the history.</p>
<h2>Decide who owns the clock</h2>
<p>Always compute <code>expires_at</code> from the database clock, not from application servers whose clocks may disagree:</p>
<pre><code class="language-sql">INSERT INTO reservations (id, profile_id, order_id, expires_at)
VALUES (:id, :profile_id, :order_id, now() + interval '15 minutes');
</code></pre>
<p>Pick the hold length from the real checkout flow, then add a small margin for payment confirmation to arrive. A hold shorter than the payment provider's confirmation delay produces the worst bug in this area: a customer pays and the profile has already been released.</p>
<h2>Treat an expired hold as dead at read time</h2>
<p>Do not rely on a background job alone to enforce expiry. A sweeper that runs every minute leaves a window where a stale hold still blocks stock. Make every read and claim check the deadline:</p>
<pre><code class="language-sql">SELECT id
FROM   profiles p
WHERE  p.plan_id = :plan_id
  AND  NOT EXISTS (
         SELECT 1 FROM reservations r
         WHERE  r.profile_id = p.id
           AND  r.status = 'ACTIVE'
           AND  r.expires_at &gt; now()
       )
  AND  p.state = 'AVAILABLE'
LIMIT  1
FOR UPDATE SKIP LOCKED;
</code></pre>
<p>With the deadline in the predicate, correctness no longer depends on the sweeper's schedule. The sweeper becomes housekeeping that keeps tables tidy and indexes small.</p>
<h2>The sweeper</h2>
<pre><code class="language-sql">UPDATE reservations
SET    status = 'EXPIRED'
WHERE  status = 'ACTIVE'
  AND  expires_at &lt;= now();
</code></pre>
<p>Run it on a short interval and make it safe to run on several nodes. The conditional <code>WHERE</code> makes a second run a no-op. Log the number of rows it expires, because a sudden jump is a signal that checkouts are failing upstream.</p>
<h2>Confirming a reservation races with expiring it</h2>
<p>The dangerous moment is payment confirmation arriving at about the same time as expiry. Resolve it with one conditional update:</p>
<pre><code class="language-sql">UPDATE reservations
SET    status = 'CONFIRMED'
WHERE  id = :id
  AND  status = 'ACTIVE'
  AND  expires_at &gt; now();
</code></pre>
<p>If zero rows change, the hold already expired. Then you have a policy decision: try to re-reserve the same profile if it is still free, pick another one, or refund. Decide it in advance and write it down rather than improvising in a handler.</p>
<h2>Extending a hold</h2>
<p>Allow extension only while active, and cap the total lifetime so a client cannot hold stock forever by pinging the endpoint:</p>
<pre><code class="language-sql">UPDATE reservations
SET    expires_at = LEAST(expires_at + interval '5 minutes', created_at + interval '30 minutes')
WHERE  id = :id AND status = 'ACTIVE' AND expires_at &gt; now();
</code></pre>
<h2>What to monitor</h2>
<p>Track the ratio of reservations that end confirmed, expired and released, plus the age of the oldest active hold. A rising expired ratio often points to a checkout bug, not user behaviour.</p>
<h2>Summary</h2>
<p>Use a separate reservations table with a partial unique index, set deadlines from the database clock, enforce expiry in the read predicate, keep a sweeper for tidiness, and settle the confirm-versus-expire race with a single conditional update.</p>
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[How to Handle Concurrent eSIM Purchases Without Inventory Collisions]]></title><description><![CDATA[Selling the same eSIM profile twice is one of the most expensive bugs in a provisioning backend. The customer who loses the race gets a failed install, a…]]></description><link>https://esimcircle.hashnode.dev/how-to-handle-concurrent-esim-purchases-without-inventory-collisions</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/how-to-handle-concurrent-esim-purchases-without-inventory-collisions</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:45:47 GMT</pubDate><content:encoded><![CDATA[<p>Selling the same eSIM profile twice is one of the most expensive bugs in a provisioning backend. The customer who loses the race gets a failed install, a support ticket and a refund. The reason it happens is simple: two requests read "available", and both believe they own the profile. This post walks through the mechanics and the fixes, with SQL you can adapt.</p>
<h2>The race, step by step</h2>
<p>A naive purchase handler looks like this:</p>
<pre><code class="language-python">def buy(plan_id, order_id):
    profile = db.query("SELECT * FROM profiles WHERE plan_id=%s AND state='AVAILABLE' LIMIT 1", plan_id)
    if not profile:
        raise OutOfStock()
    db.execute("UPDATE profiles SET state='ASSIGNED', order_id=%s WHERE id=%s", order_id, profile.id)
</code></pre>
<p>Under load, two handlers run the SELECT before either runs the UPDATE. Both get the same row. The second UPDATE overwrites the first, or both succeed if the UPDATE has no state condition. Nothing in this code is wrong in isolation. The bug lives in the gap between the read and the write.</p>
<h2>Fix 1: claim the row in a single statement</h2>
<p>The safest pattern is to select and claim in one atomic statement, using <code>FOR UPDATE SKIP LOCKED</code> so concurrent workers pick different rows instead of waiting on each other:</p>
<pre><code class="language-sql">WITH picked AS (
  SELECT id
  FROM   profiles
  WHERE  plan_id = :plan_id
    AND  state   = 'AVAILABLE'
  ORDER  BY id
  LIMIT  1
  FOR UPDATE SKIP LOCKED
)
UPDATE profiles p
SET    state = 'RESERVED',
       order_id = :order_id,
       reserved_at = now()
FROM   picked
WHERE  p.id = picked.id
RETURNING p.id;
</code></pre>
<p>If the statement returns no row, the plan is out of stock as far as this transaction can see. Two concurrent callers never get the same id, because a locked row is skipped, not waited for.</p>
<h2>Fix 2: a unique constraint as the last line of defence</h2>
<p>Even with the right query, a constraint turns a logic bug into a loud error. If an order can hold only one active profile per line item, say so in the schema:</p>
<pre><code class="language-sql">CREATE UNIQUE INDEX one_active_profile_per_order_item
ON profiles (order_item_id)
WHERE state IN ('RESERVED', 'ASSIGNED', 'DOWNLOADED');
</code></pre>
<p>A partial unique index like this costs very little and prevents a whole class of double-assignment mistakes from reaching customers.</p>
<h2>Fix 3: idempotency for the purchase itself</h2>
<p>Concurrency is not only two customers. It is also one customer whose client retries after a timeout. Key the purchase on the order or an idempotency key, and make a repeat call return the profile already reserved for that key instead of claiming a second one:</p>
<pre><code class="language-sql">INSERT INTO reservations (idempotency_key, profile_id)
VALUES (:key, :profile_id)
ON CONFLICT (idempotency_key) DO NOTHING;
</code></pre>
<p>If the insert affects zero rows, load the existing reservation and return it, and release the extra profile you just claimed.</p>
<h2>What about inventory counters?</h2>
<p>Some systems keep a separate counter such as "stock = 120" and decrement it. Counters drift. A decrement that races with a restock or a failed install gives you a number that does not match the rows. If you need a fast count for a storefront, derive it from the table with a query or a periodically refreshed view, and treat the rows as the source of truth. When you must keep a counter, decrement it in the same transaction as the claim.</p>
<h2>Testing it</h2>
<p>Write a test that starts, say, fifty concurrent buyers against ten available profiles. Assert three things: exactly ten succeed, no profile id appears twice, and the other forty get a clean out-of-stock result. Run it against a real database, because mocks cannot reproduce lock behaviour.</p>
<h2>Isolation levels in brief</h2>
<p>At <code>READ COMMITTED</code>, which is a common default, the single-statement claim above is enough. At <code>SERIALIZABLE</code> you get stronger guarantees but must be ready to retry on serialization failures. Pick deliberately and document it.</p>
<h2>Summary</h2>
<p>Claim rows atomically with <code>SKIP LOCKED</code>, back it with a partial unique index, make the purchase idempotent, and treat table rows as the source of truth for stock. Then prove it with a concurrency test.</p>
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[Building a State Machine for eSIM Profile Lifecycle Management]]></title><description><![CDATA[The profile lifecycle is a textbook case for an explicit state machine. A profile on the backend is not just a row with a status string. It is an object…]]></description><link>https://esimcircle.hashnode.dev/building-a-state-machine-for-esim-profile-lifecycle-management</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/building-a-state-machine-for-esim-profile-lifecycle-management</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:44:18 GMT</pubDate><content:encoded><![CDATA[<p>The profile lifecycle is a textbook case for an explicit state machine. A profile on the backend is not just a row with a status string. It is an object whose valid next moves depend entirely on where it is now, and where several services and retrying clients can push it around at the same time. This post is about the implementation side: how to encode the transitions so the invalid ones cannot happen.</p>
<h2>Start from the states you actually need</h2>
<p>A small, honest set of states beats a long one. A reasonable backend set looks like this:</p>
<pre><code class="language-text">AVAILABLE -&gt; RESERVED -&gt; ASSIGNED -&gt; DOWNLOADED -&gt; INSTALLED
                |            |            |
                v            v            v
            EXPIRED      RELEASED      FAILED
</code></pre>
<p>Two rules keep the set small. First, a state should answer a question the system has to act on, such as "can this be sold?" or "should we retry?". Second, device-side states like enabled and disabled are reported by the eUICC, so decide early whether you mirror them or only record the last confirmation you received.</p>
<h2>Make the transition table data, not scattered if statements</h2>
<p>The most common failure is transition logic spread across handlers, each with its own idea of what is allowed. Put it in one table:</p>
<pre><code class="language-python">ALLOWED = {
    "AVAILABLE":  {"RESERVED"},
    "RESERVED":   {"ASSIGNED", "EXPIRED", "AVAILABLE"},
    "ASSIGNED":   {"DOWNLOADED", "RELEASED", "FAILED"},
    "DOWNLOADED": {"INSTALLED", "FAILED"},
    "FAILED":     {"ASSIGNED", "RELEASED"},
    "INSTALLED":  set(),
    "EXPIRED":    {"AVAILABLE"},
    "RELEASED":   {"AVAILABLE"},
}

def can_move(src: str, dst: str) -&gt; bool:
    return dst in ALLOWED.get(src, set())
</code></pre>
<p>A table like this is easy to review, easy to test exhaustively, and easy to render as a diagram for documentation.</p>
<h2>Enforce the transition in the write, not before it</h2>
<p>Checking <code>can_move</code> in application code and then updating is a race. Two workers can both read RESERVED and both proceed. Let the database make the decision with a conditional update:</p>
<pre><code class="language-sql">UPDATE profiles
SET    state = 'ASSIGNED',
       version = version + 1,
       updated_at = now()
WHERE  id = :id
  AND  state = 'RESERVED'
  AND  version = :expected_version;
</code></pre>
<p>If the affected row count is zero, someone else moved the profile first. The caller then reloads and decides whether its intent is already satisfied or genuinely conflicts. This is optimistic concurrency, and it is cheap because transitions on a single profile are rare compared with reads.</p>
<p>You can also add a database-level guard so a bug in one service cannot write a nonsense pair. A transition table in the database plus a trigger or a composite foreign key works, though many teams find the conditional update plus tests sufficient.</p>
<h2>Record every transition as an event</h2>
<p>Keep an append-only history next to the current state:</p>
<pre><code class="language-sql">CREATE TABLE profile_transitions (
  id          bigserial PRIMARY KEY,
  profile_id  uuid        NOT NULL,
  from_state  text        NOT NULL,
  to_state    text        NOT NULL,
  cause       text        NOT NULL,
  actor       text        NOT NULL,
  request_id  text,
  created_at  timestamptz NOT NULL DEFAULT now()
);
</code></pre>
<p>Write the state update and the history row in the same transaction. When an activation fails weeks later, this table is the first place you look, and the <code>request_id</code> column ties it to traces and logs.</p>
<h2>Handle the awkward cases deliberately</h2>
<p>Idempotent re-entry: if a worker retries and the profile is already in the target state, treat it as success. Compare the current state to the target before treating a zero-row update as a conflict.</p>
<p>Terminal states: INSTALLED has no outgoing edges in the table above. If you later need to support removal or reassignment, add a new state rather than reopening a terminal one.</p>
<p>Timeouts: transitions driven by time, such as RESERVED to EXPIRED, belong to a sweeper that uses the same conditional update. The sweeper is just another actor and gets no special privileges.</p>
<p>Unknown events: if the carrier or a device reports something that does not fit the table, record it as an event and alert, instead of forcing a state change.</p>
<h2>Test the table, not just the paths</h2>
<p>Because the table is data, you can generate tests from it. For every pair of states, assert that the transition succeeds if and only if it appears in <code>ALLOWED</code>. Then add a concurrency test that fires the same transition from several workers and asserts exactly one wins.</p>
<h2>Summary</h2>
<p>Treat the lifecycle as a small state machine with one transition table, enforce each move with a conditional write, and log every change as an event. That removes most of the "how did it get into this state" mysteries before they start.</p>
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[Tracing an eSIM Activation Failure Across Multiple Services]]></title><description><![CDATA[A customer says that their eSIM does not work. The cause might be in your order service, the inventory, the supplier, the notification handler, the device…]]></description><link>https://esimcircle.hashnode.dev/tracing-an-esim-activation-failure-across-multiple-services</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/tracing-an-esim-activation-failure-across-multiple-services</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:41:39 GMT</pubDate><content:encoded><![CDATA[<p>A customer says that their eSIM does not work. The cause might be in your order service, the inventory, the supplier, the notification handler, the device, or the network between them. This post is a practical method for tracing one activation failure across services, and for building the systems that make that tracing quick. It builds on the observability post in this series.</p>
<h2>Start with the question, not the tool</h2>
<p>The first step is to put the failure into a stage. An activation passes through a limited set of stages, and each has a typical failure:</p>
<ol>
<li><strong>Order and payment:</strong> the order never reached paid, or was paid and never fulfilled.</li>
<li><strong>Allocation:</strong> no profile could be reserved, or the reservation expired.</li>
<li><strong>Supplier release:</strong> the supplier call failed or timed out, so no activation code exists.</li>
<li><strong>Delivery:</strong> the code was created but the email or page never reached the customer.</li>
<li><strong>Download:</strong> the device could not reach the SM-DP+, authentication failed, or the user abandoned the process.</li>
<li><strong>Install:</strong> the eUICC rejected the profile or ran out of space.</li>
<li><strong>Enable and attach:</strong> the profile is installed but the device is not connected to a network, or data roaming is off.</li>
</ol>
<p>The quickest way to narrow it down is to ask where the last confirmed event happened.</p>
<h2>The join key</h2>
<p>Tracing needs one identifier that every service records. In practice there are two: the order ID, which the customer and support know, and a trace ID, which the services pass along. Make sure that each log line and span carries the order ID, and that an order record stores its trace ID so that support can jump from the order to the full trace.</p>
<pre><code class="language-python">import logging, uuid
from contextvars import ContextVar

order_id_var: ContextVar[str] = ContextVar("order_id", default="-")
trace_id_var: ContextVar[str] = ContextVar("trace_id", default="-")

class ContextFilter(logging.Filter):
    def filter(self, record):
        record.order_id = order_id_var.get()
        record.trace_id = trace_id_var.get()
        return True

def start_request(order_id: str, incoming_trace_id: str | None):
    order_id_var.set(order_id)
    trace_id_var.set(incoming_trace_id or uuid.uuid4().hex)
</code></pre>
<p>Once the identifiers are attached to every log record automatically, nobody has to remember to add them.</p>
<h2>The timeline view</h2>
<p>The single most useful tool for this kind of failure is a per-order timeline: a list of every event for that order, across services, in time order. You can assemble it from the profile event table described earlier in the series, from the outbox, and from structured logs:</p>
<pre><code class="language-text">09:30:01  order-service     order.paid
09:30:02  inventory         profile.reserved         iccid=...4421
09:30:03  supplier-gateway  supplier.confirm_order   -&gt; timeout (3000 ms)
09:30:33  retry-worker      supplier.confirm_order   -&gt; ok
09:30:34  delivery          code.email_sent
09:42:10  smdp-notify      profile.downloaded
(no profile.installed event)
</code></pre>
<p>The timeline above tells a story at a glance. The supplier call needed a retry but succeeded, the code was delivered, the download happened, and the install notification never arrived. The next question is whether the install really failed or whether the notification is delayed.</p>
<h2>Checking the other side</h2>
<p>Sometimes the answer sits outside your systems. Two checks help:</p>
<ul>
<li><strong>Ask the supplier.</strong> Query the profile status at the SM-DP+ using the ICCID. If it says installed, your system missed a notification, and the fix is to apply the transition from the status you just read. If it says downloaded, the device did not finish.</li>
<li><strong>Ask the device or customer.</strong> A device error message at download time, such as a connection error, a profile-already-in-use message or a generic failure, tells you which stage failed.</li>
</ul>
<h2>Common patterns and what they mean</h2>
<ul>
<li><strong>Stuck in released, no download:</strong> the customer has not scanned the code, or the code did not reach them. Check delivery events.</li>
<li><strong>Download started, no install:</strong> a connectivity problem during the download, a device that does not support the profile, or a storage problem on the eUICC.</li>
<li><strong>Installed but no data:</strong> the profile is not enabled, data roaming is off, the APN is wrong, or the plan is for a different region.</li>
<li><strong>Repeated downloads for one code:</strong> the customer is retrying after errors, or the code has been shared.</li>
</ul>
<h2>Build the tools before the incident</h2>
<p>A few small investments pay off when something goes wrong:</p>
<ul>
<li>A support view that shows the order timeline and the current profile state without exposing the activation code.</li>
<li>A button to reconcile a profile with the supplier status, which runs the standard transition logic.</li>
<li>Saved queries for the common patterns above, such as profiles in downloaded for more than an hour.</li>
<li>A runbook that lists the stage-by-stage questions in the order to ask them.</li>
</ul>
<h2>Learn from each case</h2>
<p>When you resolve a failure, ask what signal would have shown it sooner. If a stuck profile was found by a customer instead of an alert, add the alert. If a log line was missing, add it. Over time the timeline gets fuller and the mean time to explain drops.</p>
<h2>Takeaways</h2>
<ul>
<li>Locate the failure by stage before digging into logs.</li>
<li>Carry the order ID and trace ID in every service, automatically.</li>
<li>Build a per-order timeline, and reconcile with the supplier when the local view is uncertain.</li>
<li>Invest in support tools and runbooks before incidents, not during them.</li>
</ul>
<hr />
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[Observability for an eSIM Provisioning Pipeline]]></title><description><![CDATA[A provisioning pipeline is a chain: an order service, an inventory service, a supplier gateway, a notification handler and a delivery service. When a…]]></description><link>https://esimcircle.hashnode.dev/observability-for-an-esim-provisioning-pipeline</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/observability-for-an-esim-provisioning-pipeline</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:40:04 GMT</pubDate><content:encoded><![CDATA[<p>A provisioning pipeline is a chain: an order service, an inventory service, a supplier gateway, a notification handler and a delivery service. When a customer says that their eSIM never arrived, the answer lives somewhere in that chain, and without good telemetry you find it by reading five sets of logs. This post describes the three signals you need, what to measure for a provisioning flow in particular, and how to wire it up.</p>
<h2>The three signals</h2>
<ul>
<li><strong>Metrics</strong> are numbers over time. They tell you that something is wrong and how big it is.</li>
<li><strong>Logs</strong> are records of events. They tell you what happened in a specific case.</li>
<li><strong>Traces</strong> follow one request across services. They tell you where the time and the failures went.</li>
</ul>
<p>Each answers a different question, and you need all three. Metrics alone say that failures increased. Traces show which hop. Logs show why.</p>
<h2>What to measure</h2>
<p>Start from the questions a customer, a support agent and an on-call engineer ask.</p>
<p><strong>Outcome metrics</strong> describe whether the system works:</p>
<ul>
<li>Orders fulfilled, failed and pending, per product and per supplier.</li>
<li>Time from payment to code delivery, as a histogram with percentiles (p50, p95, p99).</li>
<li>Share of delivered profiles that end up installed within a set time.</li>
</ul>
<p><strong>Pipeline metrics</strong> describe where it is stuck:</p>
<ul>
<li>Profiles by state, with the age of the oldest in each intermediate state.</li>
<li>Retry counts and the number of jobs in a failed state.</li>
<li>Queue depth and processing lag for the workers.</li>
</ul>
<p><strong>Dependency metrics</strong> describe the outside world:</p>
<ul>
<li>Supplier API latency and error rate by operation.</li>
<li>Webhook delivery success rate and delay.</li>
</ul>
<p>The age of the oldest profile in each state is one of the most useful numbers. A pile of profiles in "downloaded" for over an hour does not show up as an error anywhere else.</p>
<h2>Metrics in code</h2>
<p>Here is a sketch using the Prometheus client library for Python:</p>
<pre><code class="language-python">from prometheus_client import Counter, Histogram, Gauge

ORDERS = Counter("orders_total", "Orders by final status", ["status", "product"])
DELIVERY_SECONDS = Histogram(
    "order_delivery_seconds", "Payment to code delivery",
    buckets=(1, 5, 15, 30, 60, 300, 900, 3600),
)
SUPPLIER_CALLS = Counter(
    "supplier_calls_total", "Supplier API calls", ["operation", "outcome"])
OLDEST_PROFILE_AGE = Gauge(
    "oldest_profile_age_seconds", "Age of oldest profile per state", ["state"])
</code></pre>
<p>Keep label values to a small, fixed set. A label with an unbounded value, such as an order ID or an ICCID, creates a new time series for every value and will overload the metrics system.</p>
<h2>Structured logs</h2>
<p>Plain text lines are hard to search across services. Write one JSON object per event with a consistent set of fields:</p>
<pre><code class="language-json">{
  "ts": "2026-10-01T09:31:02.114Z",
  "level": "info",
  "service": "supplier-gateway",
  "event": "supplier.confirm_order.ok",
  "order_id": "ord_8841",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "duration_ms": 412
}
</code></pre>
<p>The order ID and the trace ID in every line are what let you pull up one customer's story across services. Be careful about what you leave out. Activation codes, matching IDs, keys and full EIDs should never be written to logs.</p>
<h2>Distributed tracing</h2>
<p>A trace is a tree of spans, each representing a unit of work such as an incoming request or an outgoing call. A trace ID, passed along in headers (the W3C <code>traceparent</code> header is the common standard), ties spans from different services together.</p>
<p>With OpenTelemetry, a provisioning step can be wrapped like this:</p>
<pre><code class="language-python">from opentelemetry import trace

tracer = trace.get_tracer("provisioning")

def confirm_with_supplier(order_id, iccid):
    with tracer.start_as_current_span("supplier.confirm_order") as span:
        span.set_attribute("order.id", order_id)
        span.set_attribute("supplier.name", "example-smdp")
        result = supplier_client.confirm(order_id, iccid)
        span.set_attribute("supplier.status", result.status)
        return result
</code></pre>
<p>The hard part is the asynchronous hand-offs. When work moves through a queue or a webhook, copy the trace context into the message so that the next service can continue the same trace. Without that, every queue hop starts a new, unconnected trace.</p>
<h2>Correlating with business identifiers</h2>
<p>Traces answer technical questions, and support asks business ones. Make sure that an order ID is searchable in your tracing and logging tools, so that an agent can enter it and get the whole path. The profile's ICCID can be added as a span attribute for the same reason, as long as your tools handle it as a high-cardinality field that is not used as a metric label.</p>
<h2>Alerts that earn their keep</h2>
<ul>
<li>Delivery time p95 above a threshold for several minutes.</li>
<li>Profiles stuck in an intermediate state beyond a limit.</li>
<li>Supplier error rate above a threshold, or a circuit breaker opening.</li>
<li>Failed jobs count increasing.</li>
<li>Inventory for a product below its low-water mark.</li>
</ul>
<p>Page on symptoms that customers feel, such as slow or failed deliveries. Send causes, like a single supplier timeout, to a dashboard or a ticket queue.</p>
<h2>Takeaways</h2>
<ul>
<li>Use metrics to detect, traces to locate and logs to explain.</li>
<li>Measure outcomes, pipeline state and dependencies, and watch the oldest-item age per state.</li>
<li>Propagate trace context through queues and webhooks.</li>
<li>Keep secrets out of telemetry and keep metric labels low-cardinality.</li>
</ul>
<hr />
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[Why Activation Codes Should Be Treated Like Secrets]]></title><description><![CDATA[The previous post covered how to protect a QR code. This one takes the step back: why an activation code belongs in the same class as an API key or a…]]></description><link>https://esimcircle.hashnode.dev/why-activation-codes-should-be-treated-like-secrets</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/why-activation-codes-should-be-treated-like-secrets</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:38:36 GMT</pubDate><content:encoded><![CDATA[<p>The previous post covered how to protect a QR code. This one takes the step back: why an activation code belongs in the same class as an API key or a password, and what engineering habits follow from that classification. The argument is short. The habits are where teams slip.</p>
<h2>What makes something a secret</h2>
<p>A useful test has three questions:</p>
<ol>
<li>Does possession of the value grant access to something valuable?</li>
<li>Is the value unguessable but otherwise unprotected, meaning nothing else checks who is using it?</li>
<li>Does leaking it cause harm that you cannot fully undo?</li>
</ol>
<p>An activation code answers yes to all three. Holding it lets you claim a paid profile, nothing in the QR code checks who is scanning, and once a profile is installed on the wrong device it cannot be moved back. That is a bearer credential, so it gets bearer-credential handling.</p>
<h2>Consequences of the classification</h2>
<p><strong>It does not go where ordinary data goes.</strong> Configuration files, source control, spreadsheets, chat messages and ticket comments are all places where secrets leak. If your support workflow involves pasting activation strings into a ticket, the workflow is the vulnerability.</p>
<p><strong>It has an owner and a lifetime.</strong> Secrets have a creation point, a short intended window of use, and an end. For an activation code, creation is the order, use is the first successful download, and the end is installation or expiry. A secret with no defined end tends to live forever in someone's inbox.</p>
<p><strong>It is handled with least privilege.</strong> Most systems that touch an order do not need the code: reporting, analytics, billing and most of support. Only the delivery path needs it. Draw that boundary in your architecture, not only in your policy.</p>
<h2>Practical rules for engineers</h2>
<ul>
<li>Fetch the secret just in time, from the secrets store, at the moment of delivery. Do not copy it into the order record, the job payload or the message queue.</li>
<li>Pass references, not values. Services exchange an ICCID or an order ID, and the one service that needs the secret resolves it.</li>
<li>Make the type system help. Wrap the value in a type that refuses to print itself:</li>
</ul>
<pre><code class="language-python">class Secret:
    __slots__ = ("_value",)

    def __init__(self, value: str):
        self._value = value

    def reveal(self) -&gt; str:
        return self._value

    def __repr__(self) -&gt; str:
        return "Secret(***)"

    __str__ = __repr__

code = Secret("LPA:1$smdp.example.com$abc123")
print(code)            # Secret(***)
logger.info("issued %s", code)   # also safe
</code></pre>
<p>Explicit <code>reveal()</code> calls are easy to find in review and in a code search, which is the point.</p>
<h2>Detecting leaks</h2>
<p>Prevention is never complete, so add detection:</p>
<ul>
<li><strong>Pattern scanning.</strong> Scan logs, error reports, source repositories and data warehouses for the <code>LPA:1</code> prefix.</li>
<li><strong>Canary values.</strong> Seed a few fake codes in test data and alert if one appears anywhere unexpected.</li>
<li><strong>Usage anomalies.</strong> Track downloads per code. A code that is attempted from several unrelated networks, or repeatedly after it was consumed, is suspicious.</li>
</ul>
<h2>Incident response</h2>
<p>Decide in advance what you do when a code leaks. A workable plan has four steps:</p>
<ol>
<li>Identify which codes were exposed, using the order and the time window.</li>
<li>Check the status of each profile. If it is not yet installed, invalidate or replace it.</li>
<li>If it was installed, work out by whom, and contact the customer when it was someone else.</li>
<li>Fix the path that leaked and add a detection rule so that it does not return.</li>
</ol>
<p>The ability to invalidate a code quickly is a design requirement. If your only option is to ask the supplier by email, you will be slow when it matters.</p>
<h2>What about the customer?</h2>
<p>Customers will treat the QR code like a coupon: a screenshot in a group chat, a photo sent to a friend who is traveling too. You cannot stop every case, but you can reduce the damage with short expiry windows, clear wording that the code works once and for one device, and a confirmation code on higher-value plans.</p>
<h2>Culture, not just controls</h2>
<p>The habit that matters most is the question "is this a secret?" at design review, asked about every identifier that grants access. Teams that ask it early end up with tokens that are generated safely, stored separately and logged by reference. Teams that do not ask it end up searching their logs after an incident.</p>
<h2>Takeaways</h2>
<ul>
<li>Classify activation codes as bearer secrets because they meet every test for one.</li>
<li>Keep them out of ordinary data paths, pass references instead of values, and resolve them only at delivery.</li>
<li>Add detection, define a response plan, and keep invalidation fast.</li>
</ul>
<hr />
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[How to Secure eSIM QR Codes and Activation Credentials]]></title><description><![CDATA[The QR code on an eSIM order is a credential. Anyone who holds the string inside it can attempt to claim the profile that it points to, and a profile can…]]></description><link>https://esimcircle.hashnode.dev/how-to-secure-esim-qr-codes-and-activation-credentials</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/how-to-secure-esim-qr-codes-and-activation-credentials</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:37:00 GMT</pubDate><content:encoded><![CDATA[<p>The QR code on an eSIM order is a credential. Anyone who holds the string inside it can attempt to claim the profile that it points to, and a profile can only be installed once. If a stranger gets the code first, the customer's eSIM is gone and the customer has paid for nothing. This post lists the threats around activation credentials and the controls that reduce them.</p>
<h2>What is actually in the QR code</h2>
<p>The code encodes an activation string with the SM-DP+ address and a matching ID, and sometimes a flag that a confirmation code is also needed. There is no encryption and no signature in it. Whoever scans it can start the download. Treat the matching ID as a bearer token.</p>
<h2>Threats</h2>
<ul>
<li><strong>Interception in transit:</strong> codes sent by email, SMS or chat can be read by anyone with access to those channels.</li>
<li><strong>Exposure in logs and tooling:</strong> application logs, error trackers, analytics tools and support screenshots often capture the full string.</li>
<li><strong>Exposure through URLs:</strong> a link such as <code>/qr?code=LPA:1$...</code> puts the secret in browser history, proxy logs and referrer headers.</li>
<li><strong>Guessing:</strong> if matching IDs are short or predictable, an attacker can try values until one is live.</li>
<li><strong>Forwarding and screenshots:</strong> a customer shares an order page with a friend or a support agent, and the code goes with it.</li>
<li><strong>Reuse after delivery:</strong> a code that remains valid after the customer has installed the profile has no reason to still be live.</li>
<li><strong>Insider access:</strong> support and operations staff can often see more than they need.</li>
</ul>
<h2>Controls at generation</h2>
<p>The matching ID should be generated with a cryptographically secure random source and be long enough that guessing is not realistic:</p>
<pre><code class="language-python">import secrets

def new_matching_id() -&gt; str:
    # 128 bits of randomness, URL-safe and easy to encode in a QR code
    return secrets.token_urlsafe(16)
</code></pre>
<p>Use the operating system's secure generator. Do not derive the ID from an order number, a timestamp or a counter.</p>
<h2>Controls at storage</h2>
<ul>
<li>Store activation strings in a secrets store or an encrypted column, apart from general order data.</li>
<li>Encrypt at rest with keys held outside the database.</li>
<li>Do not put them in application logs, analytics events or error reports. Add a log filter that redacts the <code>LPA:1$</code> pattern as a safety net:</li>
</ul>
<pre><code class="language-python">import re

LPA_PATTERN = re.compile(r"LPA:1\$[^\s\"']+")

def redact(text: str) -&gt; str:
    return LPA_PATTERN.sub("LPA:1$[REDACTED]", text)
</code></pre>
<ul>
<li>Limit who and what can read them. Support staff usually need to know whether a profile was installed, not the string itself.</li>
</ul>
<h2>Controls at delivery</h2>
<ul>
<li>Show the code only to the authenticated customer who owns the order, over HTTPS, and set cache headers that prevent storing the page:</li>
</ul>
<pre><code class="language-http">Cache-Control: no-store
Referrer-Policy: no-referrer
</code></pre>
<ul>
<li>Do not embed the secret in URLs. Serve the QR image from an authenticated endpoint, or render it directly in the page.</li>
<li>If you email the code, think about whether to email a link to an authenticated page instead of the code itself. A link to a page that requires sign-in is safer than an inbox that can be read by others.</li>
<li>Consider a confirmation code, sent through a different channel, for high-value profiles. The specification supports it, and it makes a stolen QR code useless on its own.</li>
</ul>
<h2>Controls after delivery</h2>
<ul>
<li>Mark the code as consumed once the install notification arrives, and stop showing it. After that, show instructions for managing the installed profile.</li>
<li>Set an expiry on unused codes, and reissue through an audited process.</li>
<li>Make reissuing the code a new profile or a new matching ID when you can, so the old string dies.</li>
<li>Alert on repeated failed download attempts for the same code, which can indicate guessing or sharing.</li>
</ul>
<h2>Access auditing</h2>
<p>Log the fact of access, never the value: who viewed the order's activation page and when, which support agent opened the record, and from where. That gives you a trail when a customer says that somebody else installed their profile.</p>
<h2>Testing your own exposure</h2>
<p>Search your logs, error tracker and analytics for the <code>LPA:1</code> prefix. If anything shows up, you already have a leak to clean up. Add a test that fails the build if the string appears in logged output.</p>
<h2>Takeaways</h2>
<ul>
<li>A matching ID is a bearer secret, and a QR code does not protect it.</li>
<li>Generate it with a secure random source, store it separately and keep it out of logs and URLs.</li>
<li>Deliver it only to an authenticated owner, and retire it after use.</li>
<li>Use confirmation codes and audit trails where the risk justifies them.</li>
</ul>
<hr />
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[Designing Webhooks for eSIM Activation Status Updates]]></title><description><![CDATA[When a customer buys an eSIM, their next question is whether it worked. Your backend learns the answer from events: the profile was released, a download…]]></description><link>https://esimcircle.hashnode.dev/designing-webhooks-for-esim-activation-status-updates</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/designing-webhooks-for-esim-activation-status-updates</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:35:33 GMT</pubDate><content:encoded><![CDATA[<p>When a customer buys an eSIM, their next question is whether it worked. Your backend learns the answer from events: the profile was released, a download started, an installation succeeded or failed. If other systems need to know, such as a storefront, a reseller platform or a customer app, webhooks are the usual way to tell them. This post covers how to design a webhook feed for activation status that receivers can trust and handle.</p>
<h2>What to send</h2>
<p>Send small events that describe a change, not a snapshot of everything. A useful envelope looks like this:</p>
<pre><code class="language-json">{
  "id": "evt_01HZX3K9",
  "type": "profile.installed",
  "created": "2026-10-01T09:30:12Z",
  "api_version": "2026-01",
  "data": {
    "order_id": "ord_8841",
    "iccid": "8901260000000000000",
    "state": "installed"
  }
}
</code></pre>
<p>A few decisions in that payload matter:</p>
<ul>
<li><strong>A stable event ID.</strong> Receivers use it to ignore duplicates.</li>
<li><strong>A type string</strong> that is specific and namespaced, such as <code>profile.downloaded</code>, <code>profile.installed</code> and <code>profile.failed</code>. Add new types freely, and tell receivers to ignore types they do not know.</li>
<li><strong>A version field</strong>, so you can evolve the payload without breaking existing receivers.</li>
<li><strong>Minimal data.</strong> Do not put activation codes, matching IDs or keys in a webhook. Send identifiers and let the receiver fetch details from an authenticated API if it needs them.</li>
</ul>
<h2>Delivery semantics: at least once</h2>
<p>You cannot guarantee exactly-once delivery over HTTP. If the receiver processes an event and the response is lost, you will send it again. Design for at-least-once delivery and require idempotent receivers, and document that events can arrive twice and out of order.</p>
<p>Ordering is the subtle part. Do not promise global ordering. Instead, include enough information for the receiver to ignore stale events: a sequence number per profile, or the state plus a timestamp. A receiver then keeps the highest sequence it has seen and discards anything older.</p>
<h2>Signing the payload</h2>
<p>A webhook endpoint is a public URL, so anyone can post to it. The receiver needs to verify that the call came from you. Sign the raw body with a shared secret, include a timestamp to limit replay, and send the signature in a header:</p>
<pre><code class="language-python">import hmac, hashlib, time

def sign(secret: bytes, body: bytes, timestamp: int) -&gt; str:
    signed = f"{timestamp}.".encode() + body
    return hmac.new(secret, signed, hashlib.sha256).hexdigest()

# header: X-Signature: t=1760000000,v1=&lt;hex digest&gt;
</code></pre>
<p>The receiver recomputes the digest over the raw bytes, compares with a constant-time function, and rejects timestamps older than a few minutes:</p>
<pre><code class="language-python">def verify(secret: bytes, body: bytes, header: str, tolerance=300) -&gt; bool:
    parts = dict(p.split("=", 1) for p in header.split(","))
    ts = int(parts["t"])
    if abs(time.time() - ts) &gt; tolerance:
        return False
    expected = sign(secret, body, ts)
    return hmac.compare_digest(expected, parts["v1"])
</code></pre>
<p>Verify the raw body before parsing it, since re-serializing JSON can change the bytes. Support secret rotation by accepting more than one active secret for a period.</p>
<h2>Retries and the outbox</h2>
<p>Delivery must survive crashes and slow receivers. The reliable pattern is a transactional outbox: when the state of a profile changes, write the event to an outbox table in the same transaction. A separate dispatcher reads the table and delivers.</p>
<pre><code class="language-sql">CREATE TABLE webhook_outbox (
    id            BIGSERIAL PRIMARY KEY,
    endpoint_id   BIGINT NOT NULL,
    event_id      TEXT NOT NULL,
    payload       JSONB NOT NULL,
    attempts      INTEGER NOT NULL DEFAULT 0,
    next_attempt  TIMESTAMPTZ NOT NULL DEFAULT now(),
    delivered_at  TIMESTAMPTZ,
    UNIQUE (endpoint_id, event_id)
);
</code></pre>
<p>The dispatcher treats any 2xx response as success. For anything else, including timeouts, it schedules another attempt with exponential backoff and jitter, as in the retry post of this series. After a long failure window, disable the endpoint and notify its owner so that a dead URL does not consume resources forever.</p>
<h2>Keep the receiver fast</h2>
<p>Tell consumers to acknowledge quickly and process afterwards: verify the signature, store the event, return a 2xx, and do the real work in a background job. A receiver that does slow work before replying will cause timeouts and trigger duplicate deliveries.</p>
<h2>Give receivers a way to recover</h2>
<p>People will miss events, through outages, bugs or a deleted endpoint. Offer:</p>
<ul>
<li>An API to list events in a time range, so a receiver can backfill.</li>
<li>A way to resend a specific event.</li>
<li>A status endpoint for a profile, so that a missed webhook costs a lookup, not a support ticket.</li>
</ul>
<h2>Mapping provider events</h2>
<p>The SM-DP+ notifications that tell you about installation are your inputs. Your webhook events are a translation of them into your own vocabulary, after your state machine has accepted the change. Emit an event only when the transition really happened, so that duplicates from upstream do not become duplicates for your receivers.</p>
<h2>Takeaways</h2>
<ul>
<li>Send small, versioned, signed events with stable IDs.</li>
<li>Promise at-least-once delivery and make receivers idempotent.</li>
<li>Use a transactional outbox with backoff and an endpoint-disable policy.</li>
<li>Keep secrets out of payloads and provide a backfill path.</li>
</ul>
<hr />
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[Modeling eSIM Orders and Profiles in a Relational Database]]></title><description><![CDATA[An eSIM shop needs a data model that can answer two different questions: what did the customer buy, and what is the state of the thing they were given?…]]></description><link>https://esimcircle.hashnode.dev/modeling-esim-orders-and-profiles-in-a-relational-database</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/modeling-esim-orders-and-profiles-in-a-relational-database</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:34:04 GMT</pubDate><content:encoded><![CDATA[<p>An eSIM shop needs a data model that can answer two different questions: what did the customer buy, and what is the state of the thing they were given? Mixing them in one table is the most common mistake. This post proposes a relational schema that keeps orders, profiles and their history apart, with the constraints that protect it. It uses PostgreSQL syntax, and the ideas carry over to other relational databases.</p>
<h2>The entities</h2>
<p>Five tables cover most of what you need:</p>
<ul>
<li><strong>customers:</strong> who is buying.</li>
<li><strong>products:</strong> what can be bought (a data plan for a region and a duration).</li>
<li><strong>orders:</strong> a purchase, with its commercial status.</li>
<li><strong>profiles:</strong> the physical eSIM profiles, owned by the inventory.</li>
<li><strong>order_items</strong> (or an assignment table): the link between an order and the profiles delivered for it.</li>
</ul>
<p>A separate history table records every state change of a profile.</p>
<h2>The schema</h2>
<pre><code class="language-sql">CREATE TABLE customers (
    id          BIGSERIAL PRIMARY KEY,
    email       TEXT NOT NULL UNIQUE,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE products (
    id            TEXT PRIMARY KEY,           -- e.g. 'data-5gb-30d'
    name          TEXT NOT NULL,
    region        TEXT NOT NULL,
    data_mb       INTEGER,                    -- NULL can mean unlimited
    validity_days INTEGER NOT NULL,
    active        BOOLEAN NOT NULL DEFAULT true
);

CREATE TABLE orders (
    id             BIGSERIAL PRIMARY KEY,
    customer_id    BIGINT NOT NULL REFERENCES customers(id),
    status         TEXT NOT NULL CHECK (status IN
                     ('pending','paid','fulfilled','refunded','cancelled')),
    currency       CHAR(3) NOT NULL,
    total_minor    BIGINT NOT NULL CHECK (total_minor &gt;= 0),  -- cents, not floats
    idempotency_key TEXT,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT now(),
    UNIQUE (customer_id, idempotency_key)
);

CREATE TABLE profiles (
    iccid      TEXT PRIMARY KEY,
    product_id TEXT NOT NULL REFERENCES products(id),
    state      TEXT NOT NULL CHECK (state IN
                 ('available','reserved','delivered','downloaded',
                  'installed','enabled','disabled','deleted','failed')),
    version    INTEGER NOT NULL DEFAULT 0,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE order_items (
    id         BIGSERIAL PRIMARY KEY,
    order_id   BIGINT NOT NULL REFERENCES orders(id),
    product_id TEXT   NOT NULL REFERENCES products(id),
    iccid      TEXT   UNIQUE REFERENCES profiles(iccid)   -- one profile, one item
);

CREATE TABLE profile_events (
    id          BIGSERIAL PRIMARY KEY,
    iccid       TEXT NOT NULL REFERENCES profiles(iccid),
    from_state  TEXT,
    to_state    TEXT NOT NULL,
    cause       TEXT NOT NULL,        -- 'order_paid', 'smdp_notification', ...
    occurred_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_events_iccid ON profile_events (iccid, occurred_at);
</code></pre>
<h2>Decisions worth explaining</h2>
<p><strong>Money as integers.</strong> The total is stored in minor units (cents) in an integer column. Floating point values are a classic source of rounding bugs in money.</p>
<p><strong>The ICCID as a text key.</strong> It is a string of digits where the length and any leading digits matter. A numeric type can damage it. As the key of the profiles table it is stable and meaningful to suppliers.</p>
<p><strong>One profile per order item.</strong> The unique constraint on <code>order_items.iccid</code> makes double assignment impossible at the database level, whatever the application does. The profile table does not carry an order column, because the relationship lives in the link table.</p>
<p><strong>Two separate state fields.</strong> The order has a commercial status and the profile has a technical one. A customer can have a paid order whose profile is still in the downloaded state, and a model with a single status cannot say that.</p>
<p><strong>An append-only event table.</strong> Every change of state writes a row. It costs a little storage and pays back in support work, debugging and audits. The profile row shows where things are, and the event rows show how they got there.</p>
<h2>Writing a transition</h2>
<p>The state change and its event should commit together:</p>
<pre><code class="language-sql">BEGIN;

WITH moved AS (
    UPDATE profiles
       SET state = 'installed', version = version + 1, updated_at = now()
     WHERE iccid = :iccid AND state = 'downloaded'
    RETURNING iccid
)
INSERT INTO profile_events (iccid, from_state, to_state, cause)
SELECT iccid, 'downloaded', 'installed', 'smdp_notification'
  FROM moved;

COMMIT;
</code></pre>
<p>If the update matches no row, because the profile was not in the expected state, nothing is inserted, and the application can read that as a duplicate or out-of-order event.</p>
<h2>Secrets stay elsewhere</h2>
<p>The activation code and matching ID are not columns in these tables. Put them in a store designed for secrets, keyed by ICCID, with encryption and restricted access. The relational tables can then be queried by support staff and analytics without exposing credentials.</p>
<h2>Questions the schema should answer easily</h2>
<ul>
<li>Which profile did this order receive, and what state is it in?</li>
<li>How many profiles of this product are available?</li>
<li>Show every state change for this ICCID in order.</li>
<li>Which orders are paid but not fulfilled for more than an hour?</li>
</ul>
<pre><code class="language-sql">SELECT o.id, o.created_at
  FROM orders o
  LEFT JOIN order_items oi ON oi.order_id = o.id
 WHERE o.status = 'paid'
   AND oi.iccid IS NULL
   AND o.created_at &lt; now() - interval '1 hour';
</code></pre>
<h2>Takeaways</h2>
<ul>
<li>Separate the commercial order from the technical profile.</li>
<li>Enforce one-profile-one-item with a unique constraint, not just with code.</li>
<li>Record every state change in an append-only event table.</li>
<li>Store money in minor units and keep secrets out of the relational model.</li>
</ul>
<hr />
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[How to Design a Retry Strategy for Failed Profile Provisioning]]></title><description><![CDATA[A provisioning request can fail for reasons that have nothing to do with your code: a supplier API times out, a rate limit trips, a database failover drops…]]></description><link>https://esimcircle.hashnode.dev/how-to-design-a-retry-strategy-for-failed-profile-provisioning</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/how-to-design-a-retry-strategy-for-failed-profile-provisioning</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:32:38 GMT</pubDate><content:encoded><![CDATA[<p>A provisioning request can fail for reasons that have nothing to do with your code: a supplier API times out, a rate limit trips, a database failover drops a connection. Some of those failures go away if you wait a moment, and some never will. A retry strategy is the set of rules that tells the two apart and keeps your system from making a bad situation worse. This post designs one for failed eSIM profile provisioning.</p>
<h2>Classify the failure first</h2>
<p>Retrying everything is as wrong as retrying nothing. Sort errors into three groups:</p>
<ul>
<li><strong>Transient:</strong> network timeouts, connection resets, HTTP 502, 503 and 504, and rate-limit responses. Retry these.</li>
<li><strong>Permanent:</strong> invalid input, an unknown product, an authentication failure, a profile that the supplier says does not exist. Do not retry. Fail the job and surface it.</li>
<li><strong>Ambiguous:</strong> a timeout after the request was sent. The supplier may or may not have acted. Retrying is only safe if the operation is idempotent, or after you have checked the status first.</li>
</ul>
<p>Write this classification down as code, with one function that maps an error to a decision, so the rule lives in one place:</p>
<pre><code class="language-python">from enum import Enum

class Decision(Enum):
    RETRY = 1
    FAIL = 2
    CHECK_THEN_RETRY = 3

def classify(exc_or_status) -&gt; Decision:
    if isinstance(exc_or_status, TimeoutError):
        return Decision.CHECK_THEN_RETRY      # ambiguous: did it happen?
    if exc_or_status in (429, 502, 503, 504):
        return Decision.RETRY
    if exc_or_status in (400, 401, 403, 404, 422):
        return Decision.FAIL
    return Decision.FAIL                        # unknown: do not loop blindly
</code></pre>
<p>The default for an unknown error is to fail, because a loop on an error you do not understand is how a small problem becomes an outage.</p>
<h2>Back off with jitter</h2>
<p>If many jobs fail at the same moment, retrying them all after the same delay makes them collide again. Exponential backoff spreads attempts over time, and random jitter prevents them from lining up:</p>
<pre><code class="language-python">import random

def backoff_seconds(attempt: int, base=2.0, cap=300.0) -&gt; float:
    # "full jitter": a random delay between 0 and the exponential ceiling
    ceiling = min(cap, base * (2 ** attempt))
    return random.uniform(0, ceiling)
</code></pre>
<p>A cap keeps the delay from growing without limit. If the supplier sends a <code>Retry-After</code> header, respect it instead of your own schedule.</p>
<h2>Bound the effort</h2>
<p>Every retry loop needs a stopping rule:</p>
<ul>
<li>A maximum number of attempts.</li>
<li>A maximum total time, since a customer waiting for a code does not benefit from an attempt at hour six.</li>
<li>A budget shared across jobs, such as a rate limiter or circuit breaker, so that a failing supplier is not hit by thousands of jobs at once. A circuit breaker opens after repeated failures and pauses calls for a while, then lets a trial call through.</li>
</ul>
<p>When the limit is reached, move the job to a failed state with the last error recorded. Do not drop it silently.</p>
<h2>Retries must be idempotent</h2>
<p>The reason a retry is safe is that repeating the operation has no extra effect. For provisioning, that means each attempt carries a stable idempotency key, derived from the order and the step, not generated fresh on each attempt:</p>
<pre><code class="language-python">def provisioning_key(order_id: str, step: str) -&gt; str:
    return f"{order_id}:{step}"      # same on every retry of this step
</code></pre>
<p>When a call to the supplier times out, do not retry immediately. Ask for the order's status with the stable key. If the supplier says it completed, record the result and move on. Only if it says nothing happened do you send the request again.</p>
<h2>Run retries as durable work</h2>
<p>An in-memory retry loop dies with the process. Store the retry state with the job:</p>
<pre><code class="language-sql">CREATE TABLE provisioning_jobs (
    id            BIGSERIAL PRIMARY KEY,
    order_id      TEXT NOT NULL,
    step          TEXT NOT NULL,
    state         TEXT NOT NULL,         -- pending | running | failed | done
    attempts      INTEGER NOT NULL DEFAULT 0,
    next_run_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
    last_error    TEXT,
    UNIQUE (order_id, step)
);
</code></pre>
<p>A worker claims jobs whose <code>next_run_at</code> has passed, runs them, and writes back either completion or a new <code>next_run_at</code> using the backoff function. If a worker crashes, the job is still in the table and the next one will pick it up. The unique key on order and step prevents duplicate jobs for the same work.</p>
<h2>Dead letters and humans</h2>
<p>Some jobs will exhaust their retries. Put them in a visible failed state with enough context to act: the order, the step, every error seen, and the supplier's last response. A support dashboard that lists them, and an alert when their count rises, turn a silent loss into a task for a person. Offer a way to retry manually after the cause is fixed.</p>
<h2>Metrics</h2>
<p>Track attempts per job, the share of jobs that succeed on the first try, time to success, and the count of jobs in failed. A rise in the retry rate is often the first sign of a supplier problem, before any customer reports it.</p>
<h2>Takeaways</h2>
<ul>
<li>Classify errors as transient, permanent or ambiguous before choosing to retry.</li>
<li>Use exponential backoff with jitter, a cap, and an overall time limit.</li>
<li>Keep retries idempotent with stable keys, and check status after an ambiguous failure.</li>
<li>Store retry state durably and give failed jobs a clear place to land.</li>
</ul>
<hr />
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[Using Idempotency Keys in eSIM Provisioning APIs]]></title><description><![CDATA[Provisioning APIs live on networks that fail. A client sends a request to create an eSIM order, the connection drops, and the client has no idea whether…]]></description><link>https://esimcircle.hashnode.dev/using-idempotency-keys-in-esim-provisioning-apis</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/using-idempotency-keys-in-esim-provisioning-apis</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:31:07 GMT</pubDate><content:encoded><![CDATA[<p>Provisioning APIs live on networks that fail. A client sends a request to create an eSIM order, the connection drops, and the client has no idea whether the server acted on it. It has two choices: give up and risk leaving a customer without a profile, or retry and risk a second profile. An idempotency key removes the dilemma. This post shows how to design and implement it for a provisioning API.</p>
<h2>The idea</h2>
<p>The client generates a unique key for each logical operation and sends it with the request. The server stores the result of the first execution under that key. Any later request with the same key returns the stored result and does not run the operation again. The retry becomes safe.</p>
<p>The convention is an <code>Idempotency-Key</code> HTTP header, and the key is usually a random UUID created before the first attempt:</p>
<pre><code class="language-http">POST /v1/orders HTTP/1.1
Idempotency-Key: 6f1c1d9e-3d52-4a73-9f0a-0b9d6d2f7e11
Content-Type: application/json

{"product_id": "data-5gb-30d", "customer_ref": "c_1842"}
</code></pre>
<h2>What the server must guarantee</h2>
<ol>
<li><strong>First request:</strong> execute the operation, store the key, the request fingerprint and the response, then return the response.</li>
<li><strong>Repeat with the same key and the same request:</strong> return the stored response, with the same status code.</li>
<li><strong>Repeat with the same key but a different request body:</strong> reject with an error. Reusing a key for different work is a client bug and silently returning the old result would hide it.</li>
<li><strong>Concurrent requests with the same key:</strong> only one executes. The other must wait or get a conflict response that says an attempt is in progress.</li>
</ol>
<h2>A table that does the work</h2>
<pre><code class="language-sql">CREATE TABLE idempotency_keys (
    key           TEXT NOT NULL,
    scope         TEXT NOT NULL,        -- e.g. the API client or merchant
    request_hash  TEXT NOT NULL,        -- fingerprint of the body
    status        TEXT NOT NULL,        -- in_progress | completed
    response_code INTEGER,
    response_body JSONB,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (scope, key)
);
</code></pre>
<p>The composite primary key means that the same key from two different clients does not collide, and the database itself enforces uniqueness for concurrent attempts.</p>
<h2>The handler</h2>
<pre><code class="language-python">import hashlib, json

def handle_create_order(db, scope, key, body):
    fingerprint = hashlib.sha256(
        json.dumps(body, sort_keys=True).encode()
    ).hexdigest()

    with db.transaction():
        row = db.insert_if_absent(
            "idempotency_keys",
            scope=scope, key=key,
            request_hash=fingerprint, status="in_progress",
        )
        if not row.created:                      # key seen before
            existing = db.get("idempotency_keys", scope=scope, key=key)
            if existing.request_hash != fingerprint:
                return 422, {"error": "key reused with a different request"}
            if existing.status == "in_progress":
                return 409, {"error": "request in progress, retry later"}
            return existing.response_code, existing.response_body

        order = create_order_and_allocate_profile(db, body)   # same transaction
        response = (201, {"order_id": order.id})
        db.update("idempotency_keys", scope=scope, key=key,
                  status="completed",
                  response_code=response[0], response_body=response[1])
        return response
</code></pre>
<p>The important property is that the order, the profile allocation and the stored response commit together. If anything fails, the whole transaction rolls back, the key disappears, and the client may retry as if nothing had happened.</p>
<h2>The harder part: calls to other systems</h2>
<p>A database transaction cannot cover an HTTP call to a supplier. If your handler calls the SM-DP+ to prepare a profile and then crashes before it records the result, a retry would call the supplier again. Two approaches help:</p>
<ul>
<li><strong>Pass your own idempotency key downstream.</strong> If the supplier supports it, derive a stable key from your order ID so that repeating the call is safe on their side.</li>
<li><strong>Record intent before the call, and the outcome after.</strong> Write a row that says that you are about to call, make the call, and write the result. A recovery job can finish half-done operations by asking the supplier for the order's status.</li>
</ul>
<h2>Expiry and key reuse</h2>
<p>Keys do not need to live forever. A retention window of a day or a few days is common, long enough to cover any realistic retry. Document it for API consumers, and state that keys must be unique per logical operation.</p>
<h2>Which operations need keys</h2>
<ul>
<li>Creating orders and allocating profiles: yes, always.</li>
<li>Sending activation codes by email or SMS: yes, or customers receive duplicates.</li>
<li>Refunds and cancellations: yes.</li>
<li>Pure reads: no, they are safe by nature.</li>
<li>Updates that set a value, such as setting a state to a specific value, are naturally idempotent. Updates that add to a value are not.</li>
</ul>
<h2>Takeaways</h2>
<ul>
<li>The client chooses the key, and the server stores and replays the result.</li>
<li>Store a fingerprint so that key reuse with a different body fails clearly.</li>
<li>Commit the work and the stored response in the same transaction.</li>
<li>Plan for downstream calls that a transaction cannot protect.</li>
</ul>
<hr />
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item><item><title><![CDATA[Preventing Double Assignment of eSIM Profiles in Distributed Systems]]></title><description><![CDATA[Double assignment is the failure that hurts most in a profile store: two customers are each given a working eSIM, but it is the same eSIM. Only one of them…]]></description><link>https://esimcircle.hashnode.dev/preventing-double-assignment-of-esim-profiles-in-distributed-systems</link><guid isPermaLink="true">https://esimcircle.hashnode.dev/preventing-double-assignment-of-esim-profiles-in-distributed-systems</guid><dc:creator><![CDATA[eSIMCircle]]></dc:creator><pubDate>Thu, 01 Oct 2026 00:29:40 GMT</pubDate><content:encoded><![CDATA[<p>Double assignment is the failure that hurts most in a profile store: two customers are each given a working eSIM, but it is the same eSIM. Only one of them can install it. The other has paid for something that cannot work, and the first may lose the profile when the second attempt fails or collides. This post looks at where double assignment comes from in a distributed system and the layers of protection that stop it.</p>
<h2>How it happens</h2>
<p>The usual causes are ordinary:</p>
<ul>
<li><strong>Check then act.</strong> Two requests both read "available", then both write "reserved". Without a guard, the second write silently wins.</li>
<li><strong>Retries.</strong> A client times out, sends the same request again, and the server allocates a second profile for what was one order. Or the server processes the original late and ends up with two.</li>
<li><strong>Replicas and caches.</strong> A read from a lagging replica or a stale cache says a profile is free when it is not.</li>
<li><strong>Reclaim races.</strong> A job that frees expired reservations runs just as the payment completes, and the profile goes back to the pool while it is being delivered.</li>
<li><strong>Supplier side.</strong> The upstream SM-DP+ or reseller API hands the same profile to two callers because of its own bug or an ambiguous retry.</li>
</ul>
<h2>Layer 1: make the database the arbiter</h2>
<p>The strongest protection is a single place that decides, with a guarantee. For a relational store, there are two good patterns.</p>
<p><strong>Conditional update.</strong> Change state only if it still has the value you expect, and check the affected row count:</p>
<pre><code class="language-sql">UPDATE profile_inventory
   SET state = 'reserved', order_id = :order_id
 WHERE iccid = :iccid AND state = 'available';
-- rows affected = 1 -&gt; you own it; 0 -&gt; someone else does
</code></pre>
<p><strong>Row locking.</strong> Select the row you intend to take with a lock, so that concurrent transactions queue or skip it:</p>
<pre><code class="language-sql">SELECT iccid FROM profile_inventory
 WHERE product_id = :p AND state = 'available'
 LIMIT 1
 FOR UPDATE SKIP LOCKED;
</code></pre>
<p>Both turn the question "who got it" into one atomic operation.</p>
<h2>Layer 2: uniqueness constraints</h2>
<p>Code can have bugs, and a constraint cannot be forgotten. Add a unique index that makes the bad state unrepresentable:</p>
<pre><code class="language-sql">CREATE UNIQUE INDEX uniq_profile_per_order
    ON profile_inventory (order_id)
 WHERE order_id IS NOT NULL;
</code></pre>
<p>This prevents two profiles from being attached to one order. To stop two orders getting one profile, the profile row itself has a single <code>order_id</code> column, so a second assignment is an update that fails your conditional check.</p>
<h2>Layer 3: idempotency for the order</h2>
<p>A retry of the same logical request must return the same profile, not a new one. Tie allocation to an idempotency key, which is the next post in this series, and store the result under it. The sequence is: look up the key, return the stored result if it exists, otherwise allocate and store the result in the same transaction.</p>
<h2>Layer 4: fencing for background jobs</h2>
<p>A job that reclaims expired reservations must not undo a sale in progress. Two guards work together:</p>
<ul>
<li>Reclaim only rows whose state is still reserved and whose expiry has passed, using a conditional update.</li>
<li>Have the payment path extend or confirm the reservation before it hands over the code, and fail if the row is no longer reserved for that order.</li>
</ul>
<p>If you use a lock service or lease, include a monotonically increasing token (a fencing token) with writes, and let the store reject writes that carry an older token. That protects against a paused worker waking up and acting on stale ownership.</p>
<h2>Layer 5: reconcile with the supplier</h2>
<p>Even a perfect local store cannot see the supplier's side. Run a reconciliation that compares your view with theirs: profiles you consider unsold that they consider downloaded, and the reverse. A mismatch is an incident to investigate, and the safest default is to withdraw the affected profile from sale.</p>
<h2>Reads from replicas</h2>
<p>Never make an allocation decision from a replica or a cache. Reads for display can be stale. The write that claims a profile must go to the primary and be conditional.</p>
<h2>Testing for it</h2>
<p>A concurrency test finds this class of bug quickly:</p>
<pre><code class="language-python">import concurrent.futures as cf

def test_no_double_assignment(allocate, stock=50, buyers=200):
    with cf.ThreadPoolExecutor(max_workers=32) as pool:
        results = list(pool.map(lambda i: allocate(order_id=f"o{i}"), range(buyers)))
    got = [r for r in results if r is not None]
    assert len(got) == stock                 # exactly the stock was sold
    assert len(set(got)) == len(got)         # and no profile was sold twice
</code></pre>
<p>Run it against a real database and not a mock, since the guarantee comes from the database.</p>
<h2>Takeaways</h2>
<ul>
<li>Let one atomic database operation decide who owns a profile.</li>
<li>Back it with unique constraints so that bugs fail loudly.</li>
<li>Use idempotency keys for retries and fencing for background jobs.</li>
<li>Reconcile against the supplier, since you cannot see their state.</li>
</ul>
<hr />
<p><em>About the author: I work on content and web development at <a href="https://esimcircle.com/">eSIMCircle</a>, a travel eSIM provider. This series comes from the engineering side of that work.</em></p>
]]></content:encoded></item></channel></rss>