<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Mohamed Elgohary</title>
    <description>The latest articles on DEV Community by Mohamed Elgohary (@mohamedelgohary).</description>
    <link>https://dev.to/mohamedelgohary</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1385700%2F8c43df02-7dfc-4be9-8ac2-414a5098653f.jpg</url>
      <title>DEV Community: Mohamed Elgohary</title>
      <link>https://dev.to/mohamedelgohary</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mohamedelgohary"/>
    <language>en</language>
    <item>
      <title>"Closed for maintenance" is an architecture choice</title>
      <dc:creator>Mohamed Elgohary</dc:creator>
      <pubDate>Sat, 28 Nov 2026 08:00:00 +0000</pubDate>
      <link>https://dev.to/mohamedelgohary/closed-for-maintenance-is-an-architecture-choice-3fc2</link>
      <guid>https://dev.to/mohamedelgohary/closed-for-maintenance-is-an-architecture-choice-3fc2</guid>
      <description>&lt;p&gt;You probably can't remember the last time WhatsApp or Facebook told you it was closed for an update. How they deploy internally I don't know. What I do know is the general technique for any service that runs on many servers: update a few at a time while the rest keep serving, then move on to the next few. Nobody is switched over all at once, and nobody notices.&lt;/p&gt;

&lt;p&gt;Many older systems were built differently. A system designed around a nightly batch often has to stop writes while the batch runs, because the batch needs a consistent view of the day and locking everything is the simplest way to get one. "Closed for maintenance" is the visible result of that design. It is not a law of nature.&lt;/p&gt;

&lt;p&gt;If you are designing something today, ask for zero-downtime updates from day one. Retrofitting them into a system that assumes a quiet night is far harder than building them in. Below are the seven things I would check, with the failure modes that make each one more than a checkbox.&lt;/p&gt;

&lt;p&gt;One idea runs through all of them. During a rolling deploy, version N and version N+1 run side by side, and they share everything: the database, the cache, the queues and the API clients. Every shared thing has to work with both versions, in both directions.&lt;/p&gt;

&lt;h2&gt;
  
  
  Roll out gradually, and let health checks decide
&lt;/h2&gt;

&lt;p&gt;Rolling, blue-green and canary deployments differ in how much of the fleet changes at once, but all of them need a gate that stops the rollout when something is wrong. Here is a Kubernetes-flavoured config. The same ideas exist in other orchestrators.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;apiVersion&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;apps/v1&lt;/span&gt;
&lt;span class="na"&gt;kind&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;Deployment&lt;/span&gt;
&lt;span class="na"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;api&lt;/span&gt;
&lt;span class="na"&gt;spec&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;replicas&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;6&lt;/span&gt;
  &lt;span class="na"&gt;strategy&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;type&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;RollingUpdate&lt;/span&gt;
    &lt;span class="na"&gt;rollingUpdate&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;maxSurge&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;          &lt;span class="c1"&gt;# start one new instance before stopping an old one
&lt;/span&gt;      &lt;span class="na"&gt;maxUnavailable&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;    &lt;span class="c1"&gt;# never drop below the desired replica count
&lt;/span&gt;  &lt;span class="na"&gt;selector&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;matchLabels&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s"&gt;app:&lt;/span&gt; &lt;span class="s"&gt;api&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
  &lt;span class="na"&gt;template&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;metadata&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;labels&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s"&gt;app:&lt;/span&gt; &lt;span class="s"&gt;api&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="na"&gt;spec&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;terminationGracePeriodSeconds&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;45&lt;/span&gt;   &lt;span class="c1"&gt;# covers preStop plus shutdown
&lt;/span&gt;      &lt;span class="na"&gt;containers&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="p"&gt;-&lt;/span&gt; &lt;span class="na"&gt;name&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;api&lt;/span&gt;
          &lt;span class="na"&gt;image&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;registry.example.com/api:2026-11-19&lt;/span&gt;
          &lt;span class="na"&gt;readinessProbe&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;httpGet&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s"&gt;path:&lt;/span&gt; &lt;span class="s"&gt;/ready&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;port:&lt;/span&gt; &lt;span class="mi"&gt;8080&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="na"&gt;periodSeconds&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;5&lt;/span&gt;
            &lt;span class="na"&gt;failureThreshold&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;
          &lt;span class="na"&gt;lifecycle&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;preStop&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
              &lt;span class="na"&gt;exec&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s"&gt;command:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s2"&gt;"sleep"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"10"&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;   &lt;span class="c1"&gt;# needs a sleep binary in the image
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With &lt;code&gt;maxUnavailable: 0&lt;/code&gt;, an instance that never becomes ready stalls the rollout and the old instances keep serving. That is the behavior you want.&lt;/p&gt;

&lt;p&gt;The probe is where teams go wrong. A readiness check that only returns 200 proves the process is up, not that the new version works. Gate on the things users feel: error rate and latency of the new instances compared with the old ones, after a bake period long enough to see them. Keep readiness separate from liveness. If a liveness probe depends on the database, a database blip restarts every instance at once, which turns a slow dependency into a full outage.&lt;/p&gt;

&lt;p&gt;Blue-green gives you an instant switch at the cost of roughly double capacity during the rollout. Canary sends a small share of traffic first and is only as good as the metrics you compare.&lt;/p&gt;

&lt;h2&gt;
  
  
  Drain connections before removing an instance
&lt;/h2&gt;

&lt;p&gt;When an instance is told to stop, requests are in flight. If it exits immediately, they fail. The order should be:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Stop receiving new traffic: fail the readiness check.&lt;/li&gt;
&lt;li&gt;Wait for the load balancer to notice. Endpoint removal propagates asynchronously, which is the reason for the &lt;code&gt;preStop&lt;/code&gt; pause in the config above.&lt;/li&gt;
&lt;li&gt;Stop accepting new connections and let in-flight requests finish, up to a deadline.&lt;/li&gt;
&lt;li&gt;Exit before the grace period ends, or the orchestrator kills the process anyway.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Long-lived connections need extra care. A WebSocket does not finish on its own, so the server has to close it and the client has to reconnect. If every client reconnects at the same moment, the new instances take a burst they were not sized for. Reconnect with a random delay, and close connections gradually rather than all at once.&lt;/p&gt;

&lt;h2&gt;
  
  
  Make database changes backward compatible
&lt;/h2&gt;

&lt;p&gt;This is the part that most often forces downtime. Renaming or replacing a column in one release means that during the rollout, half the fleet runs code that does not understand the schema. The pattern that avoids it is expand, migrate, contract, spread over separate releases:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- Release 1 (expand): additive only, so nothing running today can break.&lt;/span&gt;
&lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="n"&gt;lock_timeout&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'3s'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;          &lt;span class="c1"&gt;-- fail fast instead of queueing behind a long transaction&lt;/span&gt;
&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt; &lt;span class="k"&gt;ADD&lt;/span&gt; &lt;span class="k"&gt;COLUMN&lt;/span&gt; &lt;span class="n"&gt;phone_e164&lt;/span&gt; &lt;span class="kt"&gt;text&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;-- Release 2 ships code that writes both columns and reads phone_e164,&lt;/span&gt;
&lt;span class="c1"&gt;-- falling back to phone when it is NULL.&lt;/span&gt;

&lt;span class="c1"&gt;-- Backfill in small batches, repeated until it updates 0 rows.&lt;/span&gt;
&lt;span class="c1"&gt;-- normalize_phone() is a stand-in for your own function.&lt;/span&gt;
&lt;span class="k"&gt;UPDATE&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt;
&lt;span class="k"&gt;SET&lt;/span&gt;    &lt;span class="n"&gt;phone_e164&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;normalize_phone&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;phone&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;WHERE&lt;/span&gt;  &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="k"&gt;IN&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt;
    &lt;span class="k"&gt;WHERE&lt;/span&gt;  &lt;span class="n"&gt;phone_e164&lt;/span&gt; &lt;span class="k"&gt;IS&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt; &lt;span class="k"&gt;AND&lt;/span&gt; &lt;span class="n"&gt;phone&lt;/span&gt; &lt;span class="k"&gt;IS&lt;/span&gt; &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;
    &lt;span class="k"&gt;ORDER&lt;/span&gt;  &lt;span class="k"&gt;BY&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;
    &lt;span class="k"&gt;LIMIT&lt;/span&gt;  &lt;span class="mi"&gt;1000&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;-- Release 3 stops reading and writing phone.&lt;/span&gt;

&lt;span class="c1"&gt;-- Release 4 (contract): only now remove the old column.&lt;/span&gt;
&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;customers&lt;/span&gt; &lt;span class="k"&gt;DROP&lt;/span&gt; &lt;span class="k"&gt;COLUMN&lt;/span&gt; &lt;span class="n"&gt;phone&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The reason for the wait between steps is rollback. Until release 4, any earlier release can be redeployed and still works. If the column had been dropped in the same release as the code that stops using it, rolling back the code would break against the new schema.&lt;/p&gt;

&lt;p&gt;Some PostgreSQL specifics worth knowing. An &lt;code&gt;ALTER TABLE&lt;/code&gt; needs a strong lock. If a long-running transaction holds a conflicting lock, the &lt;code&gt;ALTER&lt;/code&gt; waits, and every query that arrives after it queues behind it, so a harmless-looking migration becomes an outage. That is why &lt;code&gt;lock_timeout&lt;/code&gt; is set above: fail, then retry. Adding a column with a constant default is fast since PostgreSQL 11 because it only touches the catalog; a volatile default such as &lt;code&gt;clock_timestamp()&lt;/code&gt; still rewrites the table. Adding a constraint to a large table is safer as &lt;code&gt;ADD CONSTRAINT ... NOT VALID&lt;/code&gt; followed by &lt;code&gt;VALIDATE CONSTRAINT&lt;/code&gt;, and indexes should be built with &lt;code&gt;CREATE INDEX CONCURRENTLY&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The cost is real: a rename becomes four releases. I accept that for tables that serve live traffic. For a table nobody reads during the day, a single release is fine.&lt;/p&gt;

&lt;h2&gt;
  
  
  Version your APIs and keep old mobile clients working
&lt;/h2&gt;

&lt;p&gt;On the web you control what the user runs. On mobile you do not. People stay on old versions for weeks or months, so every server release has to work with every client version you still support. Mobile releases also pass through store review, which means a fix to a broken old client is not instant.&lt;/p&gt;

&lt;p&gt;The server side of that is mostly discipline: add fields, never remove or repurpose them, and make new behavior opt-in. The client side is a tolerant reader. A client written before a new enum value existed must not crash when the server sends it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight dart"&gt;&lt;code&gt;&lt;span class="k"&gt;enum&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="n"&gt;pending&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;shipped&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;delivered&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;unknown&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

  &lt;span class="k"&gt;static&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt; &lt;span class="nf"&gt;parse&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="n"&gt;raw&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;values&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;firstWhere&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
        &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;s&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="n"&gt;raw&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="n"&gt;orElse&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;OrderStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;unknown&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
      &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The UI then shows something neutral for &lt;code&gt;unknown&lt;/code&gt; instead of throwing. Ship that behavior in the first version of the app, because it only protects clients that already contain it.&lt;/p&gt;

&lt;p&gt;Have the app send its version in a header, and log which versions still call which endpoints. That data tells you when an old endpoint can be retired. A forced-update screen is the last resort, not the plan.&lt;/p&gt;

&lt;h2&gt;
  
  
  Decouple "end of day" from availability
&lt;/h2&gt;

&lt;p&gt;Day-close, reconciliation and reports do not need a lock on the whole system. They need a consistent view of a point in time, and databases can provide that without stopping anyone. In PostgreSQL, a repeatable-read transaction sees one snapshot for its whole life:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;BEGIN&lt;/span&gt; &lt;span class="no"&gt;ISOLATION&lt;/span&gt; &lt;span class="no"&gt;LEVEL&lt;/span&gt; &lt;span class="no"&gt;REPEATABLE&lt;/span&gt; &lt;span class="no"&gt;READ&lt;/span&gt; &lt;span class="no"&gt;READ&lt;/span&gt; &lt;span class="k"&gt;ONLY&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="nb"&gt;sum&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;ledger_entries&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;business_date&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;DATE&lt;/span&gt; &lt;span class="s1"&gt;'2026-11-18'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;-- every further query in this transaction sees the same snapshot&lt;/span&gt;
&lt;span class="k"&gt;COMMIT&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The second half of the design is in the data model. Stamp each entry with a &lt;code&gt;business_date&lt;/code&gt;. Closing a day becomes a state change on that date, and anything posted afterwards goes to the next day or to a clearly marked adjustment that references the closed one. The system keeps taking writes the whole time.&lt;/p&gt;

&lt;p&gt;Run heavy reports on a read replica. A long transaction on the primary holds back cleanup of old row versions, and on a busy table that cost shows up.&lt;/p&gt;

&lt;h2&gt;
  
  
  Use feature flags so deploy and enable are separate decisions
&lt;/h2&gt;

&lt;p&gt;When shipping code and turning on behavior are one event, every deploy is a release. A flag splits them: deploy dark, enable for a small group, widen, and switch it off in seconds if it misbehaves, without a rollback.&lt;/p&gt;

&lt;p&gt;Flags have failure modes of their own. Decide what the code does when the flag service is unreachable, and keep sensible defaults compiled into the app, since mobile clients cannot wait for a network call. Remove flags once a rollout is finished, because a codebase full of stale flags has more states than anyone can test. Flags also pair with expand-contract: flipping the read path from &lt;code&gt;phone&lt;/code&gt; to &lt;code&gt;phone_e164&lt;/code&gt; becomes a flag, not a deploy.&lt;/p&gt;

&lt;h2&gt;
  
  
  Keep a rollback path you have rehearsed
&lt;/h2&gt;

&lt;p&gt;A rollback you have never run is a hope. It also has more parts than "deploy the previous version": the previous artifact must still exist, its configuration must still be valid, and the database must still work with it. The expand-contract rule above exists to keep that last part true.&lt;/p&gt;

&lt;p&gt;Rehearse it. In staging, deploy N+1 under load, roll back to N while the load continues, and measure the time and the errors. Write down the criteria for choosing between rolling back and rolling forward, so nobody invents them at 2 a.m. Wire an automatic rollback to the same metrics that gate the rollout, so a bad canary reverts without waiting for a person.&lt;/p&gt;

&lt;h2&gt;
  
  
  When the answer is a maintenance window
&lt;/h2&gt;

&lt;p&gt;Zero downtime has a price. It needs spare capacity during rollouts, more releases for schema changes, a test matrix of mixed versions, and flag hygiene. A small internal tool used by one office from nine to five may be better served by a short, announced window. The argument is not that every system needs this. It is that the window should be a decision someone made on purpose, because the alternative is the architecture making it for you.&lt;/p&gt;

&lt;p&gt;There's a 41-second Arabic version of this in my «خلف الكواليس» series: &lt;a href="https://youtube.com/shorts/UJSlV2iNrVg" rel="noopener noreferrer"&gt;https://youtube.com/shorts/UJSlV2iNrVg&lt;/a&gt;&lt;/p&gt;

</description>
      <category>devops</category>
      <category>backend</category>
      <category>postgres</category>
      <category>architecture</category>
    </item>
    <item>
      <title>AI agents and production: permissions, not prompts</title>
      <dc:creator>Mohamed Elgohary</dc:creator>
      <pubDate>Thu, 26 Nov 2026 08:00:00 +0000</pubDate>
      <link>https://dev.to/mohamedelgohary/ai-agents-and-production-permissions-not-prompts-1e89</link>
      <guid>https://dev.to/mohamedelgohary/ai-agents-and-production-permissions-not-prompts-1e89</guid>
      <description>&lt;p&gt;In July 2025, a founder building an app with an AI coding assistant told it, explicitly, not to change anything. According to press coverage at the time, it changed things anyway and deleted production data covering more than a thousand companies. Asked what happened, it reportedly hid the damage at first and then said it had "panicked". Afterwards the vendor apologised and, in the same coverage, announced it would separate its development and production databases.&lt;/p&gt;

&lt;p&gt;I am relying only on those reported facts. I don't know how that assistant was connected to the database, and I won't speculate about it. What I can say is the part you can act on: an agent that is able to write to production can delete production, whatever it was told.&lt;/p&gt;

&lt;p&gt;An instruction is something the model reads. A permission is something the database enforces. This article is about moving every important rule from the first kind to the second, using PostgreSQL for the examples. The same reasoning applies to cloud consoles, object storage and deploy tools.&lt;/p&gt;

&lt;h2&gt;
  
  
  Separate environments by credentials, not by convention
&lt;/h2&gt;

&lt;p&gt;"Use staging" in a README is a convention. A convention holds until the first time someone, or something, ignores it. A separation by credentials means the agent's connection string points at dev or staging and the network cannot reach production from there at all.&lt;/p&gt;

&lt;p&gt;The failure mode I would check first is leaked production access. Agents read files, so a production connection string sitting in an &lt;code&gt;.env&lt;/code&gt; file on the machine, in the shell environment or in a CI variable the agent can print is production access. Search for it before you start. Then give the agent its own environment with its own variables, and prove the separation by trying to cross it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;&lt;span class="c"&gt;# Run from the agent's environment. This must fail.&lt;/span&gt;
psql &lt;span class="s2"&gt;"$PROD_DATABASE_URL"&lt;/span&gt; -c &lt;span class="s2"&gt;"SELECT 1"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If that works, the separation is a convention.&lt;/p&gt;

&lt;h2&gt;
  
  
  Least privilege by default
&lt;/h2&gt;

&lt;p&gt;The agent's database role should be able to read what it needs to explore, and nothing else. Run this as the database owner in the staging database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;REVOKE&lt;/span&gt; &lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="k"&gt;SCHEMA&lt;/span&gt; &lt;span class="n"&gt;public&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="no"&gt;PUBLIC&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;   &lt;span class="c1"&gt;-- older versions let everyone create here&lt;/span&gt;

&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="no"&gt;ROLE&lt;/span&gt; &lt;span class="n"&gt;agent_ro&lt;/span&gt; &lt;span class="no"&gt;NOLOGIN&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;GRANT&lt;/span&gt; &lt;span class="no"&gt;CONNECT&lt;/span&gt; &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="k"&gt;DATABASE&lt;/span&gt; &lt;span class="n"&gt;app_staging&lt;/span&gt; &lt;span class="k"&gt;TO&lt;/span&gt; &lt;span class="n"&gt;agent_ro&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;GRANT&lt;/span&gt; &lt;span class="no"&gt;USAGE&lt;/span&gt;   &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="k"&gt;SCHEMA&lt;/span&gt; &lt;span class="n"&gt;public&lt;/span&gt; &lt;span class="k"&gt;TO&lt;/span&gt; &lt;span class="n"&gt;agent_ro&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;GRANT&lt;/span&gt; &lt;span class="k"&gt;SELECT&lt;/span&gt;  &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="k"&gt;ALL&lt;/span&gt; &lt;span class="no"&gt;TABLES&lt;/span&gt; &lt;span class="k"&gt;IN&lt;/span&gt; &lt;span class="k"&gt;SCHEMA&lt;/span&gt; &lt;span class="n"&gt;public&lt;/span&gt; &lt;span class="k"&gt;TO&lt;/span&gt; &lt;span class="n"&gt;agent_ro&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;-- Tables created later by the migration role stay readable.&lt;/span&gt;
&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;DEFAULT&lt;/span&gt; &lt;span class="no"&gt;PRIVILEGES&lt;/span&gt; &lt;span class="k"&gt;FOR&lt;/span&gt; &lt;span class="no"&gt;ROLE&lt;/span&gt; &lt;span class="n"&gt;migrator&lt;/span&gt; &lt;span class="k"&gt;IN&lt;/span&gt; &lt;span class="k"&gt;SCHEMA&lt;/span&gt; &lt;span class="n"&gt;public&lt;/span&gt;
    &lt;span class="k"&gt;GRANT&lt;/span&gt; &lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="no"&gt;TABLES&lt;/span&gt; &lt;span class="k"&gt;TO&lt;/span&gt; &lt;span class="n"&gt;agent_ro&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;-- Password comes from your secret store, never from this file.&lt;/span&gt;
&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="no"&gt;ROLE&lt;/span&gt; &lt;span class="n"&gt;agent_session&lt;/span&gt; &lt;span class="no"&gt;LOGIN&lt;/span&gt; &lt;span class="no"&gt;PASSWORD&lt;/span&gt; &lt;span class="p"&gt;:&lt;/span&gt;&lt;span class="s1"&gt;'agent_password'&lt;/span&gt; &lt;span class="k"&gt;IN&lt;/span&gt; &lt;span class="no"&gt;ROLE&lt;/span&gt; &lt;span class="n"&gt;agent_ro&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="no"&gt;ROLE&lt;/span&gt; &lt;span class="n"&gt;agent_session&lt;/span&gt; &lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="n"&gt;statement_timeout&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'10s'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="no"&gt;ROLE&lt;/span&gt; &lt;span class="n"&gt;agent_session&lt;/span&gt; &lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="n"&gt;idle_in_transaction_session_timeout&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s1"&gt;'30s'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="no"&gt;ROLE&lt;/span&gt; &lt;span class="n"&gt;agent_session&lt;/span&gt; &lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="n"&gt;default_transaction_read_only&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;on&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then verify as &lt;code&gt;agent_session&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SET&lt;/span&gt; &lt;span class="n"&gt;default_transaction_read_only&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;off&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;   &lt;span class="c1"&gt;-- the role may do this, so the grants must hold on their own&lt;/span&gt;
&lt;span class="k"&gt;DELETE&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;companies&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;-- ERROR:  permission denied for table companies&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two details matter. The grants are the control. &lt;code&gt;default_transaction_read_only&lt;/code&gt; is only a default, and a session can switch it off, so treat it as a seatbelt that catches honest mistakes. And &lt;code&gt;SELECT&lt;/code&gt; on everything means the agent can read personal data. Where that matters, grant column by column, for example &lt;code&gt;GRANT SELECT (id, created_at, status) ON orders TO agent_ro&lt;/code&gt;, or point the agent at data that contains nothing sensitive in the first place (more on that below).&lt;/p&gt;

&lt;p&gt;Migrations and destructive statements need a different role, &lt;code&gt;migrator&lt;/code&gt; in the example, that the agent never holds. The agent can write a migration file. A human, or a pipeline the agent cannot invoke, runs it with the other credential.&lt;/p&gt;

&lt;h2&gt;
  
  
  A prompt is not a control
&lt;/h2&gt;

&lt;p&gt;"Don't change anything" is a request. It enters the model as text, competes with every other instruction in the context, and may or may not be followed. Nothing about the database changes when someone types it.&lt;/p&gt;

&lt;p&gt;A useful test for any rule you rely on: if the agent ignored it, what is the worst thing that could happen? If the answer is "production data is deleted", you have a request and not a control.&lt;/p&gt;

&lt;p&gt;That applies to a code freeze in particular. A freeze is a state of your permission system: the agent's write grants are revoked, or the environment it can reach is read-only. Writing "freeze" in the chat is a wish. Prompts are still worth writing, because they steer an agent toward what you want. They are not what stops the damage when it does not comply.&lt;/p&gt;

&lt;h2&gt;
  
  
  Human approval for anything destructive
&lt;/h2&gt;

&lt;p&gt;Statements such as &lt;code&gt;DROP&lt;/code&gt;, &lt;code&gt;DELETE&lt;/code&gt; without a &lt;code&gt;WHERE&lt;/code&gt;, bulk &lt;code&gt;UPDATE&lt;/code&gt;s and data migrations should need a person. The design question is where the boundary sits.&lt;/p&gt;

&lt;p&gt;Do not place it in a filter that inspects SQL text. PostgreSQL allows data-modifying statements inside &lt;code&gt;WITH&lt;/code&gt;, so this looks like a read and is not:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;WITH&lt;/span&gt; &lt;span class="n"&gt;gone&lt;/span&gt; &lt;span class="k"&gt;AS&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;DELETE&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;companies&lt;/span&gt; &lt;span class="k"&gt;RETURNING&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="nb"&gt;count&lt;/span&gt;&lt;span class="cm"&gt;(*) FROM gone;
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A check that looks for a statement starting with &lt;code&gt;DELETE&lt;/code&gt; misses it. The boundary belongs in the role: the agent's credential cannot execute the statement, so the only path is through the approval flow, which uses a credential the agent doesn't have. An extension such as &lt;code&gt;pg_safeupdate&lt;/code&gt; can reject &lt;code&gt;UPDATE&lt;/code&gt; and &lt;code&gt;DELETE&lt;/code&gt; without a &lt;code&gt;WHERE&lt;/code&gt;. It is a good seatbelt, not the boundary.&lt;/p&gt;

&lt;p&gt;Make approvals worth reading. If a person gets forty prompts a day they will approve all forty, which is the same habit that makes confirmation dialogs useless. Keep safe work outside the flow, and show the approver the effect rather than the statement: run the proposed change on a copy inside a transaction, report the row counts, and roll back:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;BEGIN&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;DELETE&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;companies&lt;/span&gt; &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;trial_expired_at&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="kt"&gt;interval&lt;/span&gt; &lt;span class="s1"&gt;'1 year'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;-- DELETE 14   &amp;lt;- show this to the approver, then:&lt;/span&gt;
&lt;span class="k"&gt;ROLLBACK&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;"14 rows" and "all rows" read very differently.&lt;/p&gt;

&lt;h2&gt;
  
  
  A backup counts once you have restored from it
&lt;/h2&gt;

&lt;p&gt;Whether you can recover from a deletion like that is not something you know until you have done it. Schedule a restore drill:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight shell"&gt;&lt;code&gt;createdb restore_drill
pg_restore --no-owner --dbname=restore_drill latest.dump
psql restore_drill -c &lt;span class="s2"&gt;"SELECT count(*) FROM companies;"&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Write down how long it took and how far behind the data was. Those two numbers are your real recovery time and recovery point, and they are often worse than the ones on the slide.&lt;/p&gt;

&lt;p&gt;For production, also enable point-in-time recovery. Continuous WAL archiving on top of base backups lets you restore to a moment just before the bad statement, using &lt;code&gt;recovery_target_time&lt;/code&gt;. Most managed Postgres services expose this as a setting, and it needs testing as well. Restoring to a point in time rolls back everything written after it for every user. So restore to a new instance and copy the missing rows back, rather than overwriting the live database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Log what the agent does, and check its claims
&lt;/h2&gt;

&lt;p&gt;Press coverage said the assistant reportedly hid what it had done at first. Whatever was going on inside the model, the lesson is the same: an agent's description of its own actions is a claim, and claims need evidence.&lt;/p&gt;

&lt;p&gt;Log at the database. As a superuser you can set &lt;code&gt;ALTER ROLE agent_session SET log_statement = 'all'&lt;/code&gt;, and the &lt;code&gt;pgaudit&lt;/code&gt; extension gives finer control. Log at the tool layer too: every command, timestamp and result.&lt;/p&gt;

&lt;p&gt;When an agent reports that it changed nothing, check. PostgreSQL keeps cumulative counters per table, so snapshot them before the session and compare afterwards:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;SELECT&lt;/span&gt; &lt;span class="n"&gt;relname&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n_tup_ins&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n_tup_upd&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;n_tup_del&lt;/span&gt;
&lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;pg_stat_user_tables&lt;/span&gt;
&lt;span class="k"&gt;ORDER&lt;/span&gt; &lt;span class="k"&gt;BY&lt;/span&gt; &lt;span class="n"&gt;n_tup_del&lt;/span&gt; &lt;span class="k"&gt;DESC&lt;/span&gt;
&lt;span class="k"&gt;LIMIT&lt;/span&gt; &lt;span class="mi"&gt;10&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Row counts and a diff of the schema give you two more independent checks. None of them depends on what the agent says happened.&lt;/p&gt;

&lt;h2&gt;
  
  
  Develop against seeded or anonymized data
&lt;/h2&gt;

&lt;p&gt;If the agent only ever sees fake or scrubbed data, its mistakes cost nothing and real customer data stays where the strictest controls are. Generate fixtures from a script that lives in the repository, or build the dev database from production with identifying fields replaced.&lt;/p&gt;

&lt;p&gt;There are costs. Anonymization is easy to get subtly wrong: free-text columns, rare combinations of fields and foreign keys can still identify people, so review what leaves production. Seeded data rarely reproduces the odd rows and sheer volume of the real thing, so a fix that passes in dev can still fail in production, and the schema must be built from the same migrations or dev drifts away from reality. I accept those costs because the alternative is giving the agent real data to make its development environment feel realistic.&lt;/p&gt;

&lt;h2&gt;
  
  
  The cost of doing this
&lt;/h2&gt;

&lt;p&gt;Least privilege makes the agent less capable out of the box. It will ask for things it cannot do, and someone has to run the migration or approve the change. The setup takes time, and the restore drill takes more.&lt;/p&gt;

&lt;p&gt;That is the price of making the failure mode survivable. As reported, the incident needed nothing exotic: an actor with write access to production, and an instruction standing in for a control. Ruling things out is what permissions are for.&lt;/p&gt;

&lt;p&gt;There's a 31-second Arabic version of this in my «خلف الكواليس» series: &lt;a href="https://youtube.com/shorts/yB916zSffj8" rel="noopener noreferrer"&gt;https://youtube.com/shorts/yB916zSffj8&lt;/a&gt;&lt;/p&gt;

</description>
      <category>ai</category>
      <category>postgres</category>
      <category>security</category>
      <category>devops</category>
    </item>
    <item>
      <title>The car on your ride-hailing map is a guess</title>
      <dc:creator>Mohamed Elgohary</dc:creator>
      <pubDate>Tue, 24 Nov 2026 08:00:00 +0000</pubDate>
      <link>https://dev.to/mohamedelgohary/the-car-on-your-ride-hailing-map-is-a-guess-31om</link>
      <guid>https://dev.to/mohamedelgohary/the-car-on-your-ride-hailing-map-is-a-guess-31om</guid>
      <description>&lt;p&gt;The car on a ride-hailing map is not where the driver is. It is where the app guesses the driver is.&lt;/p&gt;

&lt;p&gt;The driver's phone reports a GPS position every few seconds, not continuously. If the rider's app drew each report the moment it arrived, the car would teleport from point to point. So the app animates the car from one report toward the next, and the animation is invented. Most of the time the invention is good. Sometimes the car takes a strange turn, cuts through a building and snaps back to the road. The guess was off, and the next real position corrected it.&lt;/p&gt;

&lt;p&gt;I don't know how Uber, Careem or any other app implements this, and each one tunes its own details. This article describes the general pattern and one way to build it in Kotlin with Flow, including the numbers you have to choose and the ways it fails.&lt;/p&gt;

&lt;h2&gt;
  
  
  Never render raw pings
&lt;/h2&gt;

&lt;p&gt;A ping is a measurement taken at a time. Drawing it means claiming the car was there now, but by the time it travelled from the driver's phone through a server to the rider's phone, it is already old.&lt;/p&gt;

&lt;p&gt;The fix is to animate from the last known position to the new one, over roughly the time until the next update is expected. The car is always moving toward the most recent fact and never standing on it.&lt;/p&gt;

&lt;p&gt;Two things follow. First, you display the past, slightly: the car you see is a few seconds behind the driver, so don't use the display position for anything that must be exact, such as arrival detection. Second, the animation duration matters. If it is shorter than the real gap between pings, the car arrives early and waits, which looks like stop-and-go. If it is longer, the next ping arrives mid-glide and the car lurches.&lt;/p&gt;

&lt;p&gt;So don't hard-code the duration. Track the real gaps between accepted updates, smooth them (an exponential moving average is enough) and cap the result, so one long silence does not turn into a very slow glide.&lt;/p&gt;

&lt;h2&gt;
  
  
  Trust timestamps, not arrival order
&lt;/h2&gt;

&lt;p&gt;Networks reorder and batch. After a tunnel, three updates can arrive together. A retry can deliver an old position after a new one. If you animate in arrival order, the car drives backwards for a moment.&lt;/p&gt;

&lt;p&gt;Every fix needs the time it was measured. On Android, &lt;code&gt;Location.getElapsedRealtimeNanos()&lt;/code&gt; is a monotonic device timestamp, but it is only comparable within one boot of the driver's phone, so have the server stamp the update as well. Drop anything not newer than the newest one you have accepted:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Fix&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;lat&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;lng&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;timeMs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nc"&gt;Flow&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Fix&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dropStale&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Flow&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Fix&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;flow&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;newest&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;MIN_VALUE&lt;/span&gt;
    &lt;span class="n"&gt;collect&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;fix&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;timeMs&lt;/span&gt; &lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;newest&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;newest&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;fix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;timeMs&lt;/span&gt;
            &lt;span class="nf"&gt;emit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fix&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A stale update is not worth correcting toward. It describes a place the car has already left.&lt;/p&gt;

&lt;h2&gt;
  
  
  Move along the road, not in a straight line
&lt;/h2&gt;

&lt;p&gt;If the car glides in a straight line between two pings, it cuts every corner between them. That is the building you sometimes see it drive through. For a trip with a known route, the general fix is to interpolate along the route polyline instead of across the gap.&lt;/p&gt;

&lt;p&gt;That requires map-matching: projecting each raw position onto the route. For a trip in progress, you have the polyline already, and the matching is cheap:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Find the nearest point on the route to the raw position.&lt;/li&gt;
&lt;li&gt;Only search ahead of the last matched point, with a small allowance backwards.&lt;/li&gt;
&lt;li&gt;Interpolate along the polyline from the previous match to the new one.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The second step carries most of the value. GPS error near a junction can place the driver closer to a parallel street, or to the opposite carriageway. If the search can jump anywhere on the route, the car skips ahead or flips. A search window that only moves forward keeps progress monotonic. When the route is unknown, services such as Google's Roads API (snap to roads) or Mapbox's Map Matching API can snap a sequence of points to the road network, at the cost of a network call and some latency.&lt;/p&gt;

&lt;p&gt;Map-matching can also be confidently wrong: a driver who leaves the route is, for a moment, matched back onto it. Set a distance beyond which you stop trusting the polyline and fall back to the raw position, and test it with a driver who takes a different road.&lt;/p&gt;

&lt;h2&gt;
  
  
  Derive heading from the path, then smooth it
&lt;/h2&gt;

&lt;p&gt;The raw bearing in a GPS fix comes from the device, and it jitters, especially when the car is slow or stopped. A car icon that spins at a red light looks broken.&lt;/p&gt;

&lt;p&gt;Compute heading from the path you are drawing, and only update it when the car has actually moved some metres. Then smooth the rotation, interpolating the shortest way round the circle so it does not swing 350 degrees to go from 5 to 355:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;smoothAngle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;alpha&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// Signed shortest difference in the range [-180, 180).&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;diff&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;target&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mf"&gt;540.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mf"&gt;360.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mf"&gt;180.0&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;current&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;diff&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;alpha&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mf"&gt;360.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mf"&gt;360.0&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;bearingDeg&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fromLat&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fromLng&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;toLat&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;toLng&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;dx&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;toLng&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;fromLng&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="nc"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cos&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toRadians&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fromLat&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;dy&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;toLat&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;fromLat&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toDegrees&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;atan2&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dx&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;dy&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="mf"&gt;360.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;%&lt;/span&gt; &lt;span class="mf"&gt;360.0&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The bearing function uses a flat approximation: fine over tens of metres, wrong over long distances.&lt;/p&gt;

&lt;h2&gt;
  
  
  Animate with Flow
&lt;/h2&gt;

&lt;p&gt;Here is the core of the glide. The important choice is &lt;code&gt;collectLatest&lt;/code&gt;: when a new fix arrives, the animation for the previous one is cancelled, and the next one starts from where the car is displayed, not from where the previous fix was. That one detail is what makes corrections gentle.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;CarState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;lat&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;lng&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;bearingDeg&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;stale&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Boolean&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;lerp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;b&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Double&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;b&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="n"&gt;a&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;

&lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nc"&gt;Flow&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Fix&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;glide&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;glideMs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;            &lt;span class="c1"&gt;// smoothed gap between updates&lt;/span&gt;
    &lt;span class="n"&gt;staleAfterMs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;10_000&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;frameMs&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mi"&gt;16&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;             &lt;span class="c1"&gt;// use a frame clock in production&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Flow&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;CarState&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;channelFlow&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;shown&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CarState&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;
    &lt;span class="k"&gt;this&lt;/span&gt;@&lt;span class="n"&gt;glide&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dropStale&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;collectLatest&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;fix&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt;
        &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;from&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;shown&lt;/span&gt;
            &lt;span class="o"&gt;?:&lt;/span&gt; &lt;span class="nc"&gt;CarState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;fix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lat&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lng&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="mf"&gt;0.0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;also&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;shown&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;steps&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;glideMs&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;frameMs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;coerceAtLeast&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;moved&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lat&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;fix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lat&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lng&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="n"&gt;fix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lng&lt;/span&gt;
        &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;moved&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nf"&gt;bearingDeg&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lat&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lng&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lat&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lng&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;bearingDeg&lt;/span&gt;

        &lt;span class="k"&gt;for&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="k"&gt;in&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;steps&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;i&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt; &lt;span class="n"&gt;steps&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toDouble&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;next&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;CarState&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
                &lt;span class="n"&gt;lat&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;lerp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lat&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lat&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;lng&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;lerp&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lng&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;fix&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;lng&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;t&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
                &lt;span class="n"&gt;bearingDeg&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;smoothAngle&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;shown&lt;/span&gt; &lt;span class="o"&gt;?:&lt;/span&gt; &lt;span class="n"&gt;from&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;bearingDeg&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;target&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;alpha&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="mf"&gt;0.15&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;shown&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;next&lt;/span&gt;
            &lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;next&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="nf"&gt;delay&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;frameMs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="c1"&gt;// Silence: if nothing newer arrives, this block stays suspended and&lt;/span&gt;
        &lt;span class="c1"&gt;// collectLatest cancels it when it does.&lt;/span&gt;
        &lt;span class="nf"&gt;delay&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;staleAfterMs&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;shown&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;let&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;it&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;copy&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;stale&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;true&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a sketch. In an app I would drive the frames from the UI frame clock (&lt;code&gt;withFrameNanos&lt;/code&gt; in Compose, &lt;code&gt;ValueAnimator&lt;/code&gt; in views) instead of &lt;code&gt;delay(16)&lt;/code&gt;. The structure stays the same.&lt;/p&gt;

&lt;p&gt;Some weaknesses. &lt;code&gt;collectLatest&lt;/code&gt; drops the intermediate fixes of a burst, so after a tunnel the car glides straight to the newest point and can cut a corner. If that matters, buffer the burst and play it through at increased speed. The smoothing factor of 0.15 is applied per frame, so it depends on the frame rate. And the glide is linear, which suits constant speed but not a car that has just braked.&lt;/p&gt;

&lt;h2&gt;
  
  
  Plan for silence
&lt;/h2&gt;

&lt;p&gt;Updates stop. The driver goes through a tunnel, loses signal, or the app is backgrounded. The tempting behavior is to keep the car moving, because a frozen car looks like a bug.&lt;/p&gt;

&lt;p&gt;Extrapolation is acceptable for a short time: continue along the route at the last known speed for roughly one expected interval, then stop. A car that keeps driving is a trip you invented, and the rider will act on it by walking to the pickup point or deciding whether to wait.&lt;/p&gt;

&lt;p&gt;In the code above, &lt;code&gt;delay(staleAfterMs)&lt;/code&gt; followed by &lt;code&gt;stale = true&lt;/code&gt; is where that goes (extrapolation would sit just before it). What the UI does with the flag matters more than the flag: dim the car, show the time of the last update, and do not show an ETA that implies precision you no longer have. When the next fix arrives, &lt;code&gt;collectLatest&lt;/code&gt; cancels the wait and the car glides back into place.&lt;/p&gt;

&lt;h2&gt;
  
  
  Correct gently, unless the error is large
&lt;/h2&gt;

&lt;p&gt;When a real fix disagrees with where you drew the car, easing toward it looks natural. The code does this already, because every glide starts from the displayed position.&lt;/p&gt;

&lt;p&gt;There is a limit. If the displayed position and the new fix are far apart (a different road, a reconnect after a long silence), gliding across that distance shows the car driving through the city. Beyond a distance threshold, jump instead. The threshold is a product decision based on your city's block sizes and typical GPS error. I would start from a few hundred metres and tune against recorded trips.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tune the update rate to what you can afford
&lt;/h2&gt;

&lt;p&gt;The update rate is a budget, and the driver's phone pays for it. Frequent updates use battery and mobile data. On Android, the interval you request from the fused location provider is not exact: updates can come faster, slower or in batches. Design for jitter in the arrival times rather than assuming a clock tick.&lt;/p&gt;

&lt;p&gt;Slower updates push work to the rider's phone: longer glides, more extrapolation, bigger corrections. Faster updates reduce the smoothing you need and raise the cost on the other side. I'd choose the slowest rate at which the correction jumps still look acceptable on recorded real trips, and consider making it adaptive: faster near the pickup point, slower on a long straight road.&lt;/p&gt;

&lt;p&gt;Record real trips and replay them through the pipeline, with fixes and timestamps as input and the rendered path as output. It is the only way I know to tune these numbers without driving around.&lt;/p&gt;

&lt;p&gt;There's a 43-second Arabic version of this in my «خلف الكواليس» series: &lt;a href="https://youtube.com/shorts/DNluaevHEtQ" rel="noopener noreferrer"&gt;https://youtube.com/shorts/DNluaevHEtQ&lt;/a&gt;&lt;/p&gt;

</description>
      <category>android</category>
      <category>kotlin</category>
      <category>maps</category>
      <category>mobile</category>
    </item>
    <item>
      <title>Undo Send is a delay, not an undo</title>
      <dc:creator>Mohamed Elgohary</dc:creator>
      <pubDate>Sat, 21 Nov 2026 08:00:00 +0000</pubDate>
      <link>https://dev.to/mohamedelgohary/undo-send-is-a-delay-not-an-undo-2og2</link>
      <guid>https://dev.to/mohamedelgohary/undo-send-is-a-delay-not-an-undo-2og2</guid>
      <description>&lt;p&gt;Undo Send does not recall anything. Once a message reaches someone else's mailbox, there is nothing left to pull back. What the button does is make the send late.&lt;/p&gt;

&lt;p&gt;Gmail's help page, "Unsend a sent email", describes a cancellation window you can set to 5, 10, 20 or 30 seconds. While it is open you see "Message sent" with an Undo link. How Gmail implements that internally I don't know, and I won't guess. The behavior you can observe is consistent with a simple design: hold the message, give the person a few seconds, then do the part that cannot be reversed.&lt;/p&gt;

&lt;p&gt;That design is worth copying for any action where reversing costs more than waiting: sending a message, publishing a post, placing an order, bulk-deleting records. The idea fits in a sentence. The details are where it goes wrong, so this article walks through them in Kotlin. I use Room and coroutines for concreteness. The same shape works in KMP with a different persistence layer, and in any language with a transactional store.&lt;/p&gt;

&lt;h2&gt;
  
  
  Delay the irreversible step
&lt;/h2&gt;

&lt;p&gt;There are two ways to "undo" something. You can cancel it before it happens, or you can compensate after it happened: refund the charge, mark the email as recalled, delete the post. Compensation leaves a trace and often cannot reach everyone who already saw the effect. Cancelling a job that has not run leaves nothing behind.&lt;/p&gt;

&lt;p&gt;So the first rule is about where the irreversible step sits. It moves later, behind a window, and everything the outside world can see moves with it. That includes things teams forget:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;push notifications to the recipient,&lt;/li&gt;
&lt;li&gt;webhooks and analytics events such as &lt;code&gt;message_sent&lt;/code&gt;,&lt;/li&gt;
&lt;li&gt;search indexing and "last activity" timestamps.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If your analytics fires on tap, your dashboard will count sends that were cancelled. Fire it when the state machine reaches &lt;code&gt;SENT&lt;/code&gt;, not before.&lt;/p&gt;

&lt;h2&gt;
  
  
  Keep the window short and explicit
&lt;/h2&gt;

&lt;p&gt;Every send is now late by the length of the window. For a chat app where people expect messages to land instantly, a five-second hold on every message would feel broken. This pattern earns its cost on actions that are expensive to reverse and not time-critical. It is the wrong choice for a one-time login code or an emergency alert.&lt;/p&gt;

&lt;p&gt;Two things make a window usable:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;It is visible. A pending state with a clear Undo control, and ideally the remaining time, so nobody wonders whether the thing happened.&lt;/li&gt;
&lt;li&gt;It is tunable when the stakes are high. Gmail letting you pick 5, 10, 20 or 30 seconds is one example. Timed UI is also an accessibility problem: someone using a screen reader or with limited motor control may need more time than the default, so let them have it.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Model it as a state machine with one atomic gate
&lt;/h2&gt;

&lt;p&gt;There are four states: &lt;code&gt;PENDING&lt;/code&gt;, &lt;code&gt;SENDING&lt;/code&gt;, &lt;code&gt;SENT&lt;/code&gt; and &lt;code&gt;CANCELLED&lt;/code&gt;. The timer firing and the user tapping Undo can happen in the same millisecond, so exactly one of them must win. The wrong way to write that is check-then-act:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Do not do this: another coroutine can run between the read and the write.&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="nc"&gt;SendState&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;PENDING&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nf"&gt;cancel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even with coroutines there are suspension points between the read and the write, and the timer can be driven from more than one place, such as an in-process coroutine and a WorkManager job. The state check and the state change have to be one operation. A conditional &lt;code&gt;UPDATE&lt;/code&gt; does that, and the number of affected rows tells you who won:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;enum&lt;/span&gt; &lt;span class="nf"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SendState&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="no"&gt;PENDING&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;SENDING&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;SENT&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="no"&gt;CANCELLED&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="nd"&gt;@Entity&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tableName&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"outbox"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="n"&gt;data&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;OutboxItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="nd"&gt;@PrimaryKey&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;       &lt;span class="c1"&gt;// doubles as the idempotency key&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;SendState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;sendAtMillis&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;           &lt;span class="c1"&gt;// wall-clock deadline, persisted&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;

&lt;span class="nd"&gt;@Dao&lt;/span&gt;
&lt;span class="k"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;OutboxDao&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nd"&gt;@Insert&lt;/span&gt;
    &lt;span class="n"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;OutboxItem&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;

    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"UPDATE outbox SET state = 'CANCELLED' WHERE id = :id AND state = 'PENDING'"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;cancelIfPending&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;

    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"UPDATE outbox SET state = 'SENDING' WHERE id = :id AND state = 'PENDING'"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;claimIfPending&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;

    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"UPDATE outbox SET state = 'SENT' WHERE id = :id AND state = 'SENDING'"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;markSent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Int&lt;/span&gt;

    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"SELECT * FROM outbox WHERE state IN ('PENDING', 'SENDING')"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="n"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;unfinished&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;OutboxItem&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If &lt;code&gt;cancelIfPending&lt;/code&gt; returns 1, Undo won and the send will never happen. If it returns 0, the timer won, and the UI has to say so honestly: "Too late, it was already sent". A silent no-op after a tap on Undo is worse than not offering Undo.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;SENDING&lt;/code&gt; exists because there is a stretch where Undo is no longer possible but the server has not confirmed yet. It is also the state recovery looks for.&lt;/p&gt;

&lt;h2&gt;
  
  
  Persist the pending action
&lt;/h2&gt;

&lt;p&gt;An in-memory timer is not enough. Android can kill the process during the window, and a dropped send is the worst outcome this feature can have, because the person saw "Message sent". So the item goes into storage first, and the deadline is stored as a timestamp rather than as a running timer:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;UndoableSender&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;dao&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;OutboxDao&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;MailApi&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CoroutineScope&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;now&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;System&lt;/span&gt;&lt;span class="o"&gt;::&lt;/span&gt;&lt;span class="n"&gt;currentTimeMillis&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;submit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;windowMillis&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;OutboxItem&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="no"&gt;UUID&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;randomUUID&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;toString&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;payload&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;state&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;SendState&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;PENDING&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;sendAtMillis&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="n"&gt;windowMillis&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;dao&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;insert&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                       &lt;span class="c1"&gt;// persisted before anything else&lt;/span&gt;
        &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;launch&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nf"&gt;deliver&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="n"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;undo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Boolean&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;dao&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cancelIfPending&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;

    &lt;span class="n"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;resumeAfterRestart&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;dao&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;unfinished&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;forEach&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;launch&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="nf"&gt;deliver&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="n"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;deliver&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;OutboxItem&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="nc"&gt;SendState&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;PENDING&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nf"&gt;delay&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;sendAtMillis&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nf"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;coerceAtLeast&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;dao&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;claimIfPending&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;0&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt;   &lt;span class="c1"&gt;// undone, or another driver won&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;send&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;payload&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idempotencyKey&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;dao&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;markSent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;item&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After a restart, &lt;code&gt;resumeAfterRestart&lt;/code&gt; re-reads the outbox. An item whose deadline passed while the app was dead sends immediately: the person never tapped Undo, so the intent was to send.&lt;/p&gt;

&lt;p&gt;For a real app I would add WorkManager as a backstop, enqueueing a one-time request with an initial delay equal to the window. WorkManager's delay is a minimum, not a precise timer, so it cannot be the thing that makes the window feel exact. It guarantees eventual delivery when the process is gone. The in-process coroutine gives the precise timing. Two drivers sound risky, but &lt;code&gt;claimIfPending&lt;/code&gt; is atomic, so whichever arrives second gets 0 rows and does nothing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Give every send an idempotency key
&lt;/h2&gt;

&lt;p&gt;Look at the last two lines of &lt;code&gt;deliver&lt;/code&gt;. If the process dies after &lt;code&gt;api.send&lt;/code&gt; succeeds but before &lt;code&gt;markSent&lt;/code&gt; runs, the item is still &lt;code&gt;SENDING&lt;/code&gt; on restart and gets sent again. The same happens when a request times out although the server did process it. Without protection, that is a duplicate email.&lt;/p&gt;

&lt;p&gt;The outbox row's id is the idempotency key, generated once, before anything is sent, and reused on every retry. The server enforces it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- Server side: the key is scoped to the sender and enforced by the database.&lt;/span&gt;
&lt;span class="k"&gt;CREATE&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;messages&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;id&lt;/span&gt;              &lt;span class="kt"&gt;bigint&lt;/span&gt; &lt;span class="no"&gt;GENERATED&lt;/span&gt; &lt;span class="no"&gt;ALWAYS&lt;/span&gt; &lt;span class="k"&gt;AS&lt;/span&gt; &lt;span class="no"&gt;IDENTITY&lt;/span&gt; &lt;span class="k"&gt;PRIMARY&lt;/span&gt; &lt;span class="k"&gt;KEY&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;sender_id&lt;/span&gt;       &lt;span class="kt"&gt;bigint&lt;/span&gt; &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;idempotency_key&lt;/span&gt; &lt;span class="kt"&gt;text&lt;/span&gt;   &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;body&lt;/span&gt;            &lt;span class="kt"&gt;text&lt;/span&gt;   &lt;span class="k"&gt;NOT&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="k"&gt;UNIQUE&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sender_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idempotency_key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;INSERT&lt;/span&gt; &lt;span class="k"&gt;INTO&lt;/span&gt; &lt;span class="n"&gt;messages&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sender_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idempotency_key&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;VALUES&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nv"&gt;$1&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nv"&gt;$3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="k"&gt;CONFLICT&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;sender_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idempotency_key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;DO&lt;/span&gt; &lt;span class="k"&gt;NOTHING&lt;/span&gt;
&lt;span class="k"&gt;RETURNING&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If &lt;code&gt;RETURNING&lt;/code&gt; yields no row, the key was seen before: look up the existing message and return it as if the request had just succeeded. Decide what happens when the same key arrives with a different body. I would reject it, because it means a client bug.&lt;/p&gt;

&lt;p&gt;Two more failure modes belong here. Retry only on network errors and server errors. A 4xx will not improve by repeating it, so the item needs a &lt;code&gt;FAILED&lt;/code&gt; state that the person can see, or it sits in &lt;code&gt;SENDING&lt;/code&gt; forever. And keys need a retention period at least as long as your longest retry horizon, or a late retry arrives after the key was purged and goes through twice.&lt;/p&gt;

&lt;h2&gt;
  
  
  Keep Undo reachable
&lt;/h2&gt;

&lt;p&gt;A beautifully atomic state machine is useless if the Undo control is gone when someone reaches for it. The common ways to break it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;the toast is owned by a screen, and navigating away dismisses it,&lt;/li&gt;
&lt;li&gt;it renders behind the keyboard or the system bars,&lt;/li&gt;
&lt;li&gt;it disappears on its own timer while the pending window is still open.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On the last one: in Compose, &lt;code&gt;SnackbarDuration.Short&lt;/code&gt; and &lt;code&gt;Long&lt;/code&gt; are fixed durations, not your window. Use &lt;code&gt;Indefinite&lt;/code&gt; and drive the dismissal from the deadline:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="n"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;showUndo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="n"&gt;host&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;SnackbarHostState&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;UndoableSender&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
    &lt;span class="n"&gt;windowMillis&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;coroutineScope&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;timer&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;launch&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nf"&gt;delay&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;windowMillis&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
            &lt;span class="n"&gt;host&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;currentSnackbarData&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;dismiss&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;host&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;showSnackbar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
            &lt;span class="n"&gt;message&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"Message sent"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;actionLabel&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"Undo"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
            &lt;span class="n"&gt;duration&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;SnackbarDuration&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Indefinite&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
        &lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="n"&gt;timer&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cancel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;result&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="nc"&gt;SnackbarResult&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;ActionPerformed&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;sender&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;undo&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;host&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;showSnackbar&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Too late, it was already sent"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Host the &lt;code&gt;SnackbarHostState&lt;/code&gt; above your navigation graph, at the Scaffold or activity level, so a screen change does not cancel it. Handle the keyboard with window insets. Then decide what happens when the app goes to the background. If the person can no longer reach Undo, there is no reason to keep waiting, and flushing early is a defensible choice. Whatever you pick, make it deliberate.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prefer undo over "Are you sure?"
&lt;/h2&gt;

&lt;p&gt;A confirmation dialog asks at the moment the person has just decided, and a habit forms quickly: tap through. Mistakes tend to register a moment after the action, when the result is visible. An undo window asks nothing in the common case and offers a way out in the rare one.&lt;/p&gt;

&lt;p&gt;It has limits. It cannot cover actions that must happen instantly, and a few seconds is the wrong scale for something like deleting an account. For that, the same idea works at a longer scale: a soft delete with a grace period of days, and the real deletion afterwards.&lt;/p&gt;

&lt;p&gt;There's a 34-second Arabic version of this in my «خلف الكواليس» series: &lt;a href="https://youtube.com/shorts/_fdEGjdvbks" rel="noopener noreferrer"&gt;https://youtube.com/shorts/_fdEGjdvbks&lt;/a&gt;&lt;/p&gt;

</description>
      <category>kotlin</category>
      <category>android</category>
      <category>architecture</category>
      <category>ux</category>
    </item>
    <item>
      <title>Instagram uploads your photo before you tap Share. Here's how to build that properly</title>
      <dc:creator>Mohamed Elgohary</dc:creator>
      <pubDate>Sun, 15 Nov 2026 08:23:23 +0000</pubDate>
      <link>https://dev.to/mohamedelgohary/instagram-uploads-your-photo-before-you-tap-share-heres-how-to-build-that-properly-47c1</link>
      <guid>https://dev.to/mohamedelgohary/instagram-uploads-your-photo-before-you-tap-share-heres-how-to-build-that-properly-47c1</guid>
      <description>&lt;p&gt;Open Instagram, pick a photo, write a caption, tap &lt;strong&gt;Share&lt;/strong&gt;. The post shows up almost instantly, even on a weak connection.&lt;/p&gt;

&lt;p&gt;The app isn't uploading faster than anyone else. It started uploading before you tapped Share.&lt;/p&gt;

&lt;p&gt;Instagram's co-founder Mike Krieger described this in a 2011 talk, &lt;em&gt;Secrets to Lightning Fast Mobile Design&lt;/em&gt;, under a principle he called "move bits when no one is watching". As soon as you pick the photo and move on to the caption screen, the upload starts in the background. By the time you finish typing, the bytes are on the server. Share only has to send a tiny request: "create a post with this upload and this caption". If you back out, the client cancels and the server deletes the data.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgmtaowsm94ujqmqt4ul5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgmtaowsm94ujqmqt4ul5.png" alt="Timeline: the naive flow uploads after Share; the speculative flow uploads while the user writes the caption"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The idea fits in one sentence. Building it so it is reliable, cheap and respectful of the user's data takes more care. This is how I'd design it today, as a mobile engineer who started out in QA, breaking exactly this kind of flow.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;I explained the trick in Arabic in a 25-second short: &lt;a href="https://youtube.com/shorts/NXIoam83xdY" rel="noopener noreferrer"&gt;https://youtube.com/shorts/NXIoam83xdY&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  1. Split "upload" from "post"
&lt;/h2&gt;

&lt;p&gt;The whole trick depends on one API decision: uploading media and creating a post are two separate calls.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight http"&gt;&lt;code&gt;&lt;span class="no"&gt;POST&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;v1&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;uploads&lt;/span&gt;            &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="n"&gt;image&lt;/span&gt; &lt;span class="n"&gt;bytes&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;header&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Idempotency&lt;/span&gt;&lt;span class="o"&gt;-&lt;/span&gt;&lt;span class="nc"&gt;Key&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  → &lt;span class="mi"&gt;201&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s2"&gt;"upload_id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"up_8f3c…"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"expires_at"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"…"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;

&lt;span class="no"&gt;POST&lt;/span&gt; &lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;v1&lt;/span&gt;&lt;span class="o"&gt;/&lt;/span&gt;&lt;span class="n"&gt;posts&lt;/span&gt;              &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;body&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;upload_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;caption&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; … &lt;span class="p"&gt;}&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  → &lt;span class="mi"&gt;201&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="s2"&gt;"post_id"&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s2"&gt;"…"&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The upload is an orphan until a post claims it. That gives you three properties:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Share is cheap.&lt;/strong&gt; The request on the critical path is a few hundred bytes of JSON, not megabytes of image.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Retries are safe.&lt;/strong&gt; The &lt;code&gt;Idempotency-Key&lt;/code&gt;, a hash of the processed image bytes, makes a retried or duplicated upload return the same &lt;code&gt;upload_id&lt;/code&gt; instead of storing the file twice.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Abandonment is a server concern, not a client hope&lt;/strong&gt; (see section 4).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If your backend currently takes the image and the caption in one multipart request, this is the change to make first. Nothing on the client helps until it exists.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Decide exactly when to start
&lt;/h2&gt;

&lt;p&gt;"Start early" needs a precise trigger. Start too early and you upload photos the user was only browsing. Start too late and there's no time left to hide.&lt;/p&gt;

&lt;p&gt;A good trigger is &lt;strong&gt;the moment the media is final enough&lt;/strong&gt;: the user confirmed the selection and left the crop/filter step. If edits can still happen later, you have two options:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Upload the original and send edit parameters with the post.&lt;/strong&gt; The server renders the final image. One upload, any number of edits.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Upload the rendered image and restart on change.&lt;/strong&gt; Simpler server, but every edit after the trigger cancels the in-flight upload and starts a new one. The content-hash key makes the restart cheap if the user undoes back to a version that was already uploaded.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  3. Make the upload survive the real world
&lt;/h2&gt;

&lt;p&gt;The user will lock the phone, switch apps, walk into an elevator. A speculative upload that dies on &lt;code&gt;onPause&lt;/code&gt; hides nothing.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;iOS:&lt;/strong&gt; use a background &lt;code&gt;URLSession&lt;/code&gt; with &lt;code&gt;uploadTask(with:fromFile:)&lt;/code&gt;. Background sessions only accept uploads from a file, so write the processed image to disk first. The system continues the transfer while your app is suspended and relaunches you to handle completion.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Android:&lt;/strong&gt; enqueue the upload as &lt;code&gt;WorkManager&lt;/code&gt; work, expedited, with a network constraint, so it survives process death. Keep the in-memory &lt;code&gt;Deferred&lt;/code&gt; for the fast path while the screen is open.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Flutter / KMP:&lt;/strong&gt; keep the orchestration in shared code and delegate the transfer itself to the platform mechanism above (via a plugin or &lt;code&gt;expect&lt;/code&gt;/&lt;code&gt;actual&lt;/code&gt;). A Dart &lt;code&gt;http&lt;/code&gt; call or a Ktor call on its own will not outlive the process.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Large media:&lt;/strong&gt; make it resumable (chunked with offsets, or the tus protocol), so a 40 MB video that reached 80% doesn't restart from zero after a network change.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  4. Abandoned uploads are your responsibility
&lt;/h2&gt;

&lt;p&gt;This is the part most write-ups skip. You put the user's photo on your server &lt;em&gt;before they agreed to post it&lt;/em&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Cancel is best effort.&lt;/strong&gt; When the user backs out or picks a different photo, send &lt;code&gt;DELETE /v1/uploads/{id}&lt;/code&gt;. Assume this call will sometimes never arrive: app killed, no network, battery died.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The server must clean up anyway.&lt;/strong&gt; Unclaimed uploads expire, e.g. a job that hard-deletes uploads with no post after a few hours:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;  &lt;span class="k"&gt;DELETE&lt;/span&gt; &lt;span class="k"&gt;FROM&lt;/span&gt; &lt;span class="n"&gt;uploads&lt;/span&gt;
  &lt;span class="k"&gt;WHERE&lt;/span&gt; &lt;span class="n"&gt;post_id&lt;/span&gt; &lt;span class="k"&gt;IS&lt;/span&gt; &lt;span class="kc"&gt;NULL&lt;/span&gt;
    &lt;span class="k"&gt;AND&lt;/span&gt; &lt;span class="n"&gt;created_at&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&lt;/span&gt; &lt;span class="nb"&gt;now&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="kt"&gt;interval&lt;/span&gt; &lt;span class="s1"&gt;'6 hours'&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The blob in object storage needs the same rule (a lifecycle policy on an &lt;code&gt;unclaimed/&lt;/code&gt; prefix, with the object moved on claim).&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Treat unclaimed media as untouched.&lt;/strong&gt; No thumbnails shown to anyone, no indexing, no ML pipelines, no analytics on it until a post claims it. Legally and ethically, an unshared photo is still the user's private file. Say so in your privacy policy.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  5. Don't spend the user's data plan on a guess
&lt;/h2&gt;

&lt;p&gt;A speculative upload that gets abandoned is wasted bandwidth, and on a metered connection that's the user's money.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Respect &lt;strong&gt;Low Data Mode&lt;/strong&gt; on iOS (&lt;code&gt;allowsConstrainedNetworkAccess = false&lt;/code&gt; for the speculative session) and &lt;strong&gt;metered networks&lt;/strong&gt; on Android (&lt;code&gt;ConnectivityManager.isActiveNetworkMetered&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;On those networks, either wait for Share as before, or speculatively upload a smaller rendition and send the full one only after Share.&lt;/li&gt;
&lt;li&gt;Measure the &lt;strong&gt;abandon rate&lt;/strong&gt;: if 40% of speculative uploads are never claimed, your trigger is too early.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  6. The race when Share comes first
&lt;/h2&gt;

&lt;p&gt;Sometimes the user is faster than the network. Share is tapped while the upload is at 60%.&lt;/p&gt;

&lt;p&gt;The post request must wait for the upload, not fail and not start a second one. In Kotlin coroutines the shape is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight kotlin"&gt;&lt;code&gt;&lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Composer&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Api&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;CoroutineScope&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;var&lt;/span&gt; &lt;span class="n"&gt;upload&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;Deferred&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;UploadId&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;?&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;

    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;onMediaFinal&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;file&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;File&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="n"&gt;upload&lt;/span&gt;&lt;span class="o"&gt;?&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cancel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                       &lt;span class="c1"&gt;// a different photo replaces the old one&lt;/span&gt;
        &lt;span class="n"&gt;upload&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;upload&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;file&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;idempotencyKey&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;file&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sha256&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="n"&gt;suspend&lt;/span&gt; &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;onShare&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;caption&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="nc"&gt;PostId&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;upload&lt;/span&gt; &lt;span class="o"&gt;?:&lt;/span&gt; &lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"no media"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;// waits if still running&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;createPost&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;caption&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;               &lt;span class="c1"&gt;// the only call on the critical path&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;fun&lt;/span&gt; &lt;span class="nf"&gt;onDiscard&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;val&lt;/span&gt; &lt;span class="n"&gt;pending&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;upload&lt;/span&gt; &lt;span class="o"&gt;?:&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt;
        &lt;span class="n"&gt;upload&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pending&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;isActive&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;pending&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;cancel&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;                   &lt;span class="c1"&gt;// partial upload: the server TTL removes it&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;scope&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;launch&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;runCatching&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt; &lt;span class="n"&gt;api&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;deleteUpload&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;pending&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;await&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="p"&gt;}&lt;/span&gt;  &lt;span class="c1"&gt;// finished: delete now, best effort&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pair &lt;code&gt;onShare&lt;/code&gt; with &lt;strong&gt;optimistic UI&lt;/strong&gt;: insert the post into the feed with the local image immediately and reconcile when the server answers. That's the other Krieger principle, "perform actions optimistically". If the post ultimately fails, show it in place with a retry, never a silent disappearance.&lt;/p&gt;

&lt;h2&gt;
  
  
  7. How I'd test it
&lt;/h2&gt;

&lt;p&gt;With my QA background, this is the matrix I'd run before trusting it:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Scenario&lt;/th&gt;
&lt;th&gt;Expected&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Share after upload finished&lt;/td&gt;
&lt;td&gt;Post appears instantly; only one &lt;code&gt;POST /posts&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Share at 60% upload&lt;/td&gt;
&lt;td&gt;UI shows the post immediately; post call waits, then succeeds&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Double-tap Share&lt;/td&gt;
&lt;td&gt;One post (idempotent post creation, button disabled after first tap)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Pick photo A, then switch to B&lt;/td&gt;
&lt;td&gt;A cancelled + deleted; only B claimed&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Back out of composer&lt;/td&gt;
&lt;td&gt;
&lt;code&gt;DELETE&lt;/code&gt; sent; if offline, upload expires via TTL&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Airplane mode mid-upload, then back&lt;/td&gt;
&lt;td&gt;Upload resumes, not restarts&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;App killed mid-upload (iOS + Android)&lt;/td&gt;
&lt;td&gt;Transfer completes in the background or resumes on next launch&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Low Data Mode / metered network&lt;/td&gt;
&lt;td&gt;No speculative full-size upload&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Same photo uploaded twice&lt;/td&gt;
&lt;td&gt;Same &lt;code&gt;upload_id&lt;/code&gt; (content-hash key)&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Unclaimed upload after TTL&lt;/td&gt;
&lt;td&gt;Row and blob both gone&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;h2&gt;
  
  
  8. Measure the thing users feel
&lt;/h2&gt;

&lt;p&gt;The metric is not upload speed. It is &lt;strong&gt;time from Share tap to post visible&lt;/strong&gt;, at p50 and p95, split by network type. Track it next to the &lt;strong&gt;abandon rate&lt;/strong&gt; and &lt;strong&gt;wasted bytes&lt;/strong&gt;. Then you can tell whether the speculation is paying for itself.&lt;/p&gt;

&lt;h2&gt;
  
  
  The point
&lt;/h2&gt;

&lt;p&gt;The app isn't faster. It spends time the user was going to spend anyway: picking a filter, writing a caption, thinking. A lot of what feels "fast" in good apps is really about where the waiting goes.&lt;/p&gt;




&lt;p&gt;&lt;em&gt;I'm Mohamed Elgohary, a Mobile &amp;amp; Product Engineer (Flutter, Kotlin Multiplatform, Android). I build apps from the idea to the store, and I test them the way a QA engineer would. «خلف الكواليس» is my Arabic short series about the tricks behind apps you use every day.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>mobile</category>
      <category>android</category>
      <category>ios</category>
      <category>ux</category>
    </item>
    <item>
      <title>Valid product, wrong supplier: moving an ownership rule into the database</title>
      <dc:creator>Mohamed Elgohary</dc:creator>
      <pubDate>Tue, 10 Nov 2026 21:54:05 +0000</pubDate>
      <link>https://dev.to/mohamedelgohary/valid-product-wrong-supplier-moving-an-ownership-rule-into-the-database-3o92</link>
      <guid>https://dev.to/mohamedelgohary/valid-product-wrong-supplier-moving-an-ownership-rule-into-the-database-3o92</guid>
      <description>&lt;h2&gt;
  
  
  TL;DR
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;In EgyGomla, a request for a sample could name supplier A and a product that belonged to supplier B. Every constraint in the database accepted it.&lt;/li&gt;
&lt;li&gt;The only thing refusing that pair was one &lt;code&gt;if&lt;/code&gt; in one repository method. It protected that code path and no other.&lt;/li&gt;
&lt;li&gt;A composite foreign key on &lt;code&gt;(product_id, supplier_organization_id)&lt;/code&gt; moved the rule into the database. I kept the application check so callers still get a clear error.&lt;/li&gt;
&lt;li&gt;No production incident is behind this. I found it while reviewing the schema. The fix enforces one stored relationship, not authorization in general.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The shape of the problem
&lt;/h2&gt;

&lt;p&gt;EgyGomla is a B2B sourcing platform I built for Egyptian traders. Two of its tables hold sample requests and private-label requests. Each row carries a supplier and, optionally, a catalogue product.&lt;/p&gt;

&lt;p&gt;The foreign key from the request to the product named only &lt;code&gt;catalog_products(id)&lt;/code&gt;. So the database asked one question: does this product exist? It never asked whether the product belongs to the supplier written on the same row.&lt;/p&gt;

&lt;p&gt;That means a row pairing supplier A with supplier B's product satisfied every constraint. The product is real and the supplier is real. The relationship is wrong.&lt;/p&gt;

&lt;p&gt;There was a check. The service verified that the product belonged to the supplier, so requests arriving through the API were covered. My own migration comment describes the weakness better than I would paraphrase it: that check protects the path that runs it and no other, "not a repair script, not a future module, not a bulk import".&lt;/p&gt;

&lt;p&gt;I want to be exact about the scope here. I did not find corrupted data, and no customer was affected. This was a gap between what the application enforced and what the database enforced, and the cheapest time to close it is before something writes a bad row.&lt;/p&gt;

&lt;h2&gt;
  
  
  The fix
&lt;/h2&gt;

&lt;p&gt;The rule moves into the key itself. First, the parent table gets a unique constraint over the pair, so the pair can be referenced:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="s2"&gt;"catalog_products"&lt;/span&gt;
  &lt;span class="k"&gt;ADD&lt;/span&gt; &lt;span class="k"&gt;CONSTRAINT&lt;/span&gt; &lt;span class="s2"&gt;"catalog_products_id_supplier_organization_id_key"&lt;/span&gt;
  &lt;span class="k"&gt;UNIQUE&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"supplier_organization_id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This adds no real restriction. &lt;code&gt;id&lt;/code&gt; is already the primary key, so any &lt;code&gt;(id, supplier)&lt;/code&gt; pair is already unique. The constraint exists only so that something can point at the pair.&lt;/p&gt;

&lt;p&gt;Then the child tables swap their single-column key for a composite one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="s2"&gt;"sample_requests"&lt;/span&gt;
  &lt;span class="k"&gt;DROP&lt;/span&gt; &lt;span class="k"&gt;CONSTRAINT&lt;/span&gt; &lt;span class="s2"&gt;"sample_requests_product_id_fkey"&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="s2"&gt;"sample_requests"&lt;/span&gt;
  &lt;span class="k"&gt;ADD&lt;/span&gt; &lt;span class="k"&gt;CONSTRAINT&lt;/span&gt; &lt;span class="s2"&gt;"sample_requests_product_id_supplier_organization_id_fkey"&lt;/span&gt;
  &lt;span class="k"&gt;FOREIGN&lt;/span&gt; &lt;span class="k"&gt;KEY&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"product_id"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"supplier_organization_id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="k"&gt;REFERENCES&lt;/span&gt; &lt;span class="s2"&gt;"catalog_products"&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s2"&gt;"supplier_organization_id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
  &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="k"&gt;DELETE&lt;/span&gt; &lt;span class="k"&gt;RESTRICT&lt;/span&gt; &lt;span class="k"&gt;ON&lt;/span&gt; &lt;span class="k"&gt;UPDATE&lt;/span&gt; &lt;span class="k"&gt;CASCADE&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The same change is applied to &lt;code&gt;private_label_requests&lt;/code&gt;. Now the database checks the whole pair against the catalogue. In plain terms: the pair &lt;code&gt;(P42, A)&lt;/code&gt; must exist as a row in the products table, and the row says P42 belongs to B, so the insert is rejected.&lt;/p&gt;

&lt;p&gt;The pairing becomes a fact the database keeps rather than an invariant the application remembers.&lt;/p&gt;

&lt;p&gt;In a LinkedIn post I called the column &lt;code&gt;supplier_id&lt;/code&gt; to keep the example simple. The real column is &lt;code&gt;supplier_organization_id&lt;/code&gt;, because suppliers are organizations in this schema.&lt;/p&gt;

&lt;h2&gt;
  
  
  The detail that is easy to get wrong: NULL
&lt;/h2&gt;

&lt;p&gt;A request can name no product at all. In that case &lt;code&gt;product_id&lt;/code&gt; is NULL, and the request should be valid.&lt;/p&gt;

&lt;p&gt;PostgreSQL foreign keys default to &lt;code&gt;MATCH SIMPLE&lt;/code&gt;: if any referencing column is NULL, the constraint is not checked. That is exactly what "this request names no product" should mean, so the default is what I want here. With &lt;code&gt;MATCH FULL&lt;/code&gt;, a request with no product would also have to null out its supplier, which is wrong.&lt;/p&gt;

&lt;p&gt;I mention it because the same rule cuts the other way. When a column must always be checked, &lt;code&gt;MATCH SIMPLE&lt;/code&gt; plus a nullable column means a writer that forgets to fill it in switches the check off without any error. The same trap came up again on a different constraint, and the answer there was to make the column &lt;code&gt;NOT NULL&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Keep the service check
&lt;/h2&gt;

&lt;p&gt;I did not delete the application validation. The database is the backstop and the service is the user interface of the rule.&lt;/p&gt;

&lt;p&gt;If the composite key rejects an insert, the driver surfaces a foreign-key error. The repository translates it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Simplified from the repository.&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nf"&gt;errorCode&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="s2"&gt;"P2003"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;DomainValidationError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s2"&gt;"The linked product is not available for this supplier."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The message is deliberately vague. It does not confirm whether the product exists or who owns it. A buyer probing product ids should not be able to learn another supplier's catalogue from the difference between two error messages.&lt;/p&gt;

&lt;h2&gt;
  
  
  What this does not do
&lt;/h2&gt;

&lt;p&gt;It would be easy to oversell this, so here are the limits:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It enforces one stored relationship: this product belongs to this supplier. It is not an authorization system and it is not tenant isolation. Something still has to decide who may create a request in the first place.&lt;/li&gt;
&lt;li&gt;It does not fix a wrong row by changing the supplier. It rejects the pair.&lt;/li&gt;
&lt;li&gt;It cannot see anything outside the columns it covers. A different table with a similar mismatch needs its own key.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How I would test it
&lt;/h2&gt;

&lt;p&gt;A constraint that is never exercised is a comment. The test I want is at the database level, with direct inserts that skip the application entirely:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- Illustrative test cases, not from the repository.&lt;/span&gt;
&lt;span class="c1"&gt;-- 1. Valid pair: product P42 owned by B, request names (P42, B)  -&amp;gt; accepted&lt;/span&gt;
&lt;span class="c1"&gt;-- 2. Wrong pair: product P42 owned by B, request names (P42, A)  -&amp;gt; rejected&lt;/span&gt;
&lt;span class="c1"&gt;-- 3. No product: request names (NULL, A)                         -&amp;gt; accepted&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The three cases cover the intended path, the bug, and the NULL semantics. If all three behave, the rule lives in the schema and a future import script cannot bypass it by forgetting to call the service.&lt;/p&gt;

&lt;h2&gt;
  
  
  The same pattern, applied wider
&lt;/h2&gt;

&lt;p&gt;The same mechanism shows up again in a later migration that makes a wrong-type tenant unrepresentable. Without it, the database would store a buyer organization as the owner of a catalogue product, or a supplier in the buyer slot of a request. Only whichever query remembered to filter on type would refuse it. The fix has three parts: a denormalised type column on the child row, a composite foreign key that forces it to agree with the organization row, and a &lt;code&gt;CHECK&lt;/code&gt; that pins it to the one legal value for that slot.&lt;/p&gt;

&lt;p&gt;The schema now has thirteen composite keys on &lt;code&gt;organizations(id, type)&lt;/code&gt;. A later design decision about marketplace accounts, which I describe in another article, refuses to disturb that network.&lt;/p&gt;

&lt;p&gt;Two practical habits came out of that migration:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Count the violators first.&lt;/strong&gt; Before adding the constraints, the migration counts existing rows that would break them and refuses to continue, naming the table and the number, rather than failing on a bare constraint name or silently changing data. A violation there is a real finding and gets reconciled by hand.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Mind the deploy order.&lt;/strong&gt; The new columns are &lt;code&gt;NOT NULL&lt;/code&gt; with no default, so every writer has to supply them before the migration runs. An older release cannot insert into those tables once the migration is applied.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  The costs
&lt;/h2&gt;

&lt;p&gt;Composite keys are not free:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The parent needs a unique constraint over the extra pair, and every referencing table carries a copy of the owning column.&lt;/li&gt;
&lt;li&gt;Every writer must supply the extra columns, including seeds, scripts and old app versions.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;ON UPDATE CASCADE&lt;/code&gt; means a change to the referenced column ripples down. That is intended, and it also means ownership changes need thought.&lt;/li&gt;
&lt;li&gt;Error handling needs work, because a raw foreign-key violation is a poor message.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;I accept those costs for rules where a silent wrong row is expensive and the data is shared across tenants.&lt;/p&gt;

&lt;h2&gt;
  
  
  A review you can run on your own schema
&lt;/h2&gt;

&lt;p&gt;Look for tables that store a tenant or owner id next to a resource id. For each one, ask whether the database proves that the resource belongs to that tenant, or only proves that both exist. If it is the second, write down which code paths currently enforce the rule, and which could write around them: imports, repair scripts, admin tools, new services.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I'd do differently
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Add the composite key when the table is created.&lt;/strong&gt; Retrofitting it took a separate migration that dropped and recreated the key. A new table can have it from the first commit.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Test at the database level from the start.&lt;/strong&gt; I would write the three insert cases as part of the migration review.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Look for the pattern earlier.&lt;/strong&gt; The same shape existed in other tables, and a wider migration followed two days later.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Say what the fix covers.&lt;/strong&gt; It closes one gap. Calling it tenant isolation would be wrong.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mohamed Elgohary, Mobile &amp;amp; Product Engineer, Cairo. mohamedelgohary.dev&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published on my site: &lt;a href="https://mohamedelgohary.dev/writing/valid-product-wrong-supplier-composite-foreign-key/" rel="noopener noreferrer"&gt;mohamedelgohary.dev&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>postgres</category>
      <category>database</category>
      <category>prisma</category>
      <category>backend</category>
    </item>
    <item>
      <title>Tested like a QA engineer: how I release mobile apps</title>
      <dc:creator>Mohamed Elgohary</dc:creator>
      <pubDate>Tue, 10 Nov 2026 21:53:36 +0000</pubDate>
      <link>https://dev.to/mohamedelgohary/tested-like-a-qa-engineer-how-i-release-mobile-apps-57fa</link>
      <guid>https://dev.to/mohamedelgohary/tested-like-a-qa-engineer-how-i-release-mobile-apps-57fa</guid>
      <description>&lt;h2&gt;
  
  
  TL;DR
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;I have a QA/SDET background alongside my mobile engineering work, and I release apps the way a tester would: assume the happy path works and spend the effort on everything around it.&lt;/li&gt;
&lt;li&gt;My public release checklist has 34 items in six sections: build, testing, backend, App Store, Google Play, and launch day. Store rules on it were checked against the official pages on 28 September 2026.&lt;/li&gt;
&lt;li&gt;The habits that matter most: test the exact artifact you ship, refuse every permission, break the network on purpose, upgrade from the version people already have, and keep the API compatible with old installs.&lt;/li&gt;
&lt;li&gt;A checklist is not a test suite. It tells you what to test and what evidence to keep.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Where this comes from
&lt;/h2&gt;

&lt;p&gt;From August 2024 to August 2025 I worked as a Software Development Engineer in Test for TAKADOM AL-IRAQ (TTech), on a freelance basis. I was responsible for mobile, web and API testing on public-service products, and I built the Kotlin and Selenium automation for the Naftcom project, with API and regression coverage around its citizen and station workflows. That code is in a private repository, so I will not describe it in detail here.&lt;/p&gt;

&lt;p&gt;I also build mobile apps. At Apps Square I am responsible for the mobile apps of several products, from setup and architecture through testing and delivery. At Inside Tech I built Bismar's customer and seller apps on Kotlin Multiplatform as the only mobile engineer on them, and both have public App Store and Google Play listings.&lt;/p&gt;

&lt;p&gt;The testing habit comes with me. When I read a feature now, my first question is still what happens when this fails.&lt;/p&gt;

&lt;h2&gt;
  
  
  Test the thing you ship
&lt;/h2&gt;

&lt;p&gt;A debug build proves very little about a release. The checklist is explicit that I test the signed release build with production settings, because code shrinking and release configuration can break things a debug build never shows.&lt;/p&gt;

&lt;p&gt;A few items sit next to that one because they fail in the same quiet way:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Version and build number.&lt;/strong&gt; Every upload needs a higher build number than the last (&lt;code&gt;versionCode&lt;/code&gt; on Android, the build number on iOS), and the visible version must match the release notes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Signing keys.&lt;/strong&gt; Use Play App Signing so a lost upload key can be reset. Back up keys and passwords outside the repository.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Crash symbols.&lt;/strong&gt; Upload the R8/ProGuard mapping file and the iOS dSYMs to the crash reporter. Without them, production stack traces are unreadable and the first real crash is a guessing game.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;No debug leftovers.&lt;/strong&gt; Check base URLs, feature flags, verbose logging of personal data and hidden test menus in the release configuration.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Devices and the upgrade path
&lt;/h2&gt;

&lt;p&gt;The checklist asks for real devices at both ends: at least the oldest OS version you support and the newest, a small screen and a large one.&lt;/p&gt;

&lt;p&gt;The upgrade test is the one I would least like to skip. Install the version on the store today, create some data, then update. Sessions, saved settings and local data must survive. A fresh install can be perfect while the person who has used the app for a year loses their session.&lt;/p&gt;

&lt;h2&gt;
  
  
  Failure paths first
&lt;/h2&gt;

&lt;p&gt;This is where the QA background shows most. The checklist's network item reads: test slow, offline and flaky connections, confirm loading, retry and error states work, and make sure a repeated request never creates a duplicate order or payment.&lt;/p&gt;

&lt;p&gt;That last clause is the important one. A retry that works is only half of the feature. The other half is that the retry is safe.&lt;/p&gt;

&lt;p&gt;Here is a small example from a Flutter app I worked on, Fueler. The home screen loaded account, wallet and product data in parallel, and also resolved the user's location to find nearby stations. The original code waited for all of it before showing the page, so a slow location fix hid the wallet balance behind a loading state, even though the wallet never needed coordinates.&lt;/p&gt;

&lt;p&gt;The test that guards the fix does what a tester would do: it delays one dependency on purpose.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight dart"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Simplified from the project's test file.&lt;/span&gt;
&lt;span class="n"&gt;locationResolver&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;delay&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;seconds&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt; &lt;span class="c1"&gt;// a genuinely cold fix&lt;/span&gt;
&lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="n"&gt;loading&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cubit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;load&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nc"&gt;Future&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;void&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;delayed&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;milliseconds&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;400&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="c1"&gt;// The screen is already usable before the location fix lands:&lt;/span&gt;
&lt;span class="nf"&gt;expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cubit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;status&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;HomeStatus&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;loaded&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nf"&gt;expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cubit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;profile&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_profile&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nf"&gt;expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cubit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;products&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;_products&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="c1"&gt;// ...and the sections that need coordinates say so honestly:&lt;/span&gt;
&lt;span class="nf"&gt;expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cubit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;locationAccess&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;LocationAccess&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;unknown&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="nf"&gt;expect&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;cubit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;state&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stations&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;isEmpty&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A second test in the same group asserts that a warm fix emits exactly one state per refresh, so the stations section does not flash back to "locating". I did not measure device timing or any conversion effect, and I am not claiming one. The point is the shape of the test: slow down one thing, and check what the rest of the screen is allowed to do.&lt;/p&gt;

&lt;h2&gt;
  
  
  Permissions and the language you read in
&lt;/h2&gt;

&lt;p&gt;Camera, location and notifications each need a test for the case people forget: the person taps Don't Allow. The app should keep working and explain why it needs the permission.&lt;/p&gt;

&lt;p&gt;The checklist also treats Arabic as a test configuration, not a translation task: mirrored layouts, mixed Arabic and English text, and the system font size at its largest. Right-to-left bugs are easy to miss when you read the interface in only one language.&lt;/p&gt;

&lt;h2&gt;
  
  
  The API is part of the release
&lt;/h2&gt;

&lt;p&gt;A mobile release is half a backend release, and the half people forget is the old app. People update slowly, so the checklist asks that the API keep serving the installed version: old endpoints and response shapes keep working, or a forced-update path ships first.&lt;/p&gt;

&lt;p&gt;A minimum-supported-version check lets you retire a broken build without waiting for everyone to update. And on the data side: run migrations on a copy of production data first, and take a backup before the release.&lt;/p&gt;

&lt;p&gt;I carry the same habit into my own tooling. PostSync Pro, an open-source Compose Desktop toolkit I built, sends REST requests, runs bounded assertions and validates responses against an OpenAPI specification. It is published as a beta, and the screens that still use simulated data are labelled as previews.&lt;/p&gt;

&lt;h2&gt;
  
  
  A regression pass on what hurts most
&lt;/h2&gt;

&lt;p&gt;I do not try to retest everything. The checklist says to run a regression pass on the flows that matter most: sign-up, sign-in, checkout or booking, and anything a support call would be about. Notifications and deep links get their own check: they should open the right screen from a closed app, from the background and when signed out.&lt;/p&gt;

&lt;h2&gt;
  
  
  Store rules are test cases too
&lt;/h2&gt;

&lt;p&gt;Both stores publish rules that read like requirements, so they become checks. A few from the checklist:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;App Store:&lt;/strong&gt; build with the required SDK (iOS 26 SDK or later, since 28 April 2026); keep App Privacy details in line with what the app and its SDKs collect; give App Review a working demo account and keep the backend on during review; offer account deletion inside the app; if you offer a third-party sign-in, offer an equivalent option such as Sign in with Apple; answer the encryption question in &lt;code&gt;Info.plist&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Google Play:&lt;/strong&gt; keep the Data safety form in line with the app; meet the target API requirement; provide sign-in details for review that keep working (reusable, no one-time code, not expiring); and for a new personal developer account, run the closed test before applying for production.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Dates and thresholds change, so the checklist links each rule to the official page and records when it was last checked. Re-check before you rely on any of it.&lt;/p&gt;

&lt;p&gt;A store review is a separate gate with its own rules. It does not tell me whether checkout survives a flaky connection, so it never replaces my own testing.&lt;/p&gt;

&lt;h2&gt;
  
  
  Evidence, not memory
&lt;/h2&gt;

&lt;p&gt;After a release I want to answer what was tested, on what, and what happened. A short record is enough. This is an illustrative template, not a file from a specific project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;release&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;2.4.0 (build 118)&lt;/span&gt;
&lt;span class="na"&gt;artifact&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;signed release build, production config&lt;/span&gt;
&lt;span class="na"&gt;devices&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="p"&gt;[&lt;/span&gt;&lt;span class="s"&gt;oldest&lt;/span&gt; &lt;span class="s"&gt;supported&lt;/span&gt; &lt;span class="s"&gt;OS&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;newest&lt;/span&gt; &lt;span class="s"&gt;OS&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;small&lt;/span&gt; &lt;span class="s"&gt;screen&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="s"&gt;large&lt;/span&gt; &lt;span class="s"&gt;screen&lt;/span&gt;&lt;span class="p"&gt;]&lt;/span&gt;
&lt;span class="na"&gt;upgrade_from_live&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;passed, session and local data kept&lt;/span&gt;
&lt;span class="na"&gt;network&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;slow / offline / flaky checked, repeated request created no duplicate&lt;/span&gt;
&lt;span class="na"&gt;permissions&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;camera, location, notifications denied once each&lt;/span&gt;
&lt;span class="na"&gt;arabic_rtl_large_text&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;checked&lt;/span&gt;
&lt;span class="na"&gt;regression&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;sign-in, checkout, support-call flows&lt;/span&gt;
&lt;span class="na"&gt;backend&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;old endpoints still served, min-version check in place&lt;/span&gt;
&lt;span class="na"&gt;symbols&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;mapping file and dSYMs uploaded&lt;/span&gt;
&lt;span class="na"&gt;rollout&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;staged, halt criteria agreed&lt;/span&gt;
&lt;span class="na"&gt;owner_first_72h&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="s"&gt;named&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Writing it down changes behaviour: a skipped line is visible, and "I thought we checked that" stops being an answer.&lt;/p&gt;

&lt;h2&gt;
  
  
  Launch day and after
&lt;/h2&gt;

&lt;p&gt;The release is not over when the build is live. The last section of the checklist asks for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;release notes written for people, in every store language, saying what changed and whether they need to do anything;&lt;/li&gt;
&lt;li&gt;someone who watches the first 72 hours, with an owner for crash reports, store reviews and support messages;&lt;/li&gt;
&lt;li&gt;a plan for a bad release, since an installed update stays until you ship a fix: keep a hotfix path and server-side switches ready;&lt;/li&gt;
&lt;li&gt;release analytics verified in production, firing once with the right values and respecting consent.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On Google Play the checklist also asks for a staged rollout: release to a small percentage first and halt if the crash or ANR rate rises. That applies to updates, not to a first release.&lt;/p&gt;

&lt;h2&gt;
  
  
  What I'd do differently
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Turn more of the list into automated checks.&lt;/strong&gt; Some items, like the upgrade path and the repeated-request test, are repeatable enough that a person should not have to remember them.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Attach an owner and evidence to each item.&lt;/strong&gt; A checkbox says someone looked. It does not say what they saw.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Treat the list as a starting point.&lt;/strong&gt; It is written for mobile apps with a backend. Some projects will skip items, and a project with payments will need more.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keep the store rules fresh.&lt;/strong&gt; They change, and the "reviewed on" date is only honest if someone updates it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Be precise about what the list is.&lt;/strong&gt; It is my public checklist, not a record that every item was done on every release.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mohamed Elgohary, Mobile &amp;amp; Product Engineer, Cairo. mohamedelgohary.dev&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published on my site: &lt;a href="https://mohamedelgohary.dev/writing/tested-like-a-qa-engineer-how-i-release-mobile-apps/" rel="noopener noreferrer"&gt;mohamedelgohary.dev&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>mobile</category>
      <category>testing</category>
      <category>flutter</category>
      <category>qa</category>
    </item>
    <item>
      <title>One identity, many roles: what I got wrong about marketplace accounts</title>
      <dc:creator>Mohamed Elgohary</dc:creator>
      <pubDate>Tue, 10 Nov 2026 21:52:52 +0000</pubDate>
      <link>https://dev.to/mohamedelgohary/one-identity-many-roles-what-i-got-wrong-about-marketplace-accounts-2fdd</link>
      <guid>https://dev.to/mohamedelgohary/one-identity-many-roles-what-i-got-wrong-about-marketplace-accounts-2fdd</guid>
      <description>&lt;h2&gt;
  
  
  TL;DR
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;I built EgyGomla, a B2B sourcing platform for Egyptian traders, with a separate email, account and password for each side of the market: buyers on one subdomain, suppliers on another.&lt;/li&gt;
&lt;li&gt;A wholesaler buys from factories and sells to retailers. My "clean" design made the people the product is for pay the most.&lt;/li&gt;
&lt;li&gt;The better model: the email is the person, and "buyer" and "supplier" are roles. In the data model that is one user with at most one buyer organization and one supplier organization, linked but never merged, with self-dealing blocked in the database.&lt;/li&gt;
&lt;li&gt;This is a decided design (ADR-0013, status Accepted, 14 August 2026), and the migrations for it are written in the repo. It is not a claim that traders can do this in production today.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  What I built first
&lt;/h2&gt;

&lt;p&gt;EgyGomla helps Egyptian traders find manufacturers and suppliers, browse wholesale catalogues and request quotations. I built it end to end: web apps, dashboards, backend and Flutter apps. The public website is live; the mobile apps are not on the stores yet.&lt;/p&gt;

&lt;p&gt;The production edge is one Caddy config, a hostname per surface:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;egygomla.com&lt;/code&gt;: the public marketing site&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;app.egygomla.com&lt;/code&gt;: the buyer application&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;factory.egygomla.com&lt;/code&gt;: the supplier portal&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;admin.egygomla.com&lt;/code&gt;: the platform console&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;api.egygomla.com&lt;/code&gt;: the HTTP API&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;id.egygomla.com&lt;/code&gt;: Keycloak, the OIDC issuer&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;On top of that split I decided every role gets its own email. It felt tidy: each role in its own place, the data separate.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where it breaks: the wholesaler
&lt;/h2&gt;

&lt;p&gt;The product's own audience line names factories, importers, and wholesale and retail traders. A wholesaler, by definition of the trade, buys from the factory and sells to the retailer. That person is both sides of the market.&lt;/p&gt;

&lt;p&gt;Under my first design, that trader needs a second email, a second account, a second password, and keeps switching between them. I was penalising my best users for being my best users.&lt;/p&gt;

&lt;p&gt;The cost is not only friction. Two accounts share no catalogue, conversations, reviews or history, and the platform cannot know they are one business, which matters once you think about abuse.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the big marketplaces do
&lt;/h2&gt;

&lt;p&gt;On Amazon you buy on the main site, and Amazon's own seller registration guide says you can sell with the same email and password as your customer account. noon follows the same shape: you shop on its main site, and the seller portal is a separate surface on its own domain (&lt;code&gt;login.noon.partners&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;The pattern in both: one login, the buyer experience as the front door, selling as a second surface you opt into.&lt;/p&gt;

&lt;h2&gt;
  
  
  Identity is not a role
&lt;/h2&gt;

&lt;p&gt;An email represents a person. "Buyer" and "supplier" are things that person does. Tie identity to role and anyone with more than one role pays for it, while everyone else never notices.&lt;/p&gt;

&lt;h2&gt;
  
  
  Where the constraint actually lived
&lt;/h2&gt;

&lt;p&gt;I assumed the data model was the problem. &lt;code&gt;OrganizationType&lt;/code&gt; is &lt;code&gt;BUYER | SUPPLIER | PLATFORM&lt;/code&gt;, and a schema comment says one organization row cannot be both at once. But the enum was not what blocked wholesalers. Most of the multi-role machinery already existed:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Membership is many-to-many in practice, with a unique key on &lt;code&gt;(userId, organizationId)&lt;/code&gt;, so one person can belong to a buyer organization and a supplier organization at once.&lt;/li&gt;
&lt;li&gt;An endpoint returns a list of the person's organizations, not one.&lt;/li&gt;
&lt;li&gt;The guard resolves the acting organization on every request from a header, then checks the membership, its status, and that the organization's type matches the route.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What blocked the wholesaler was one rule in onboarding:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight typescript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// onboarding service (paraphrased from the ADR)&lt;/span&gt;
&lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;onboarding&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;kind&lt;/span&gt; &lt;span class="o"&gt;===&lt;/span&gt; &lt;span class="s2"&gt;"PROVISIONED"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
  &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;DomainValidationError&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;
    &lt;span class="s2"&gt;"This account already exists. Use an invitation to join another organization."&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt;
  &lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That rule was deliberate. An earlier decision used &lt;code&gt;(issuer, subject)&lt;/code&gt; from the identity provider as the natural idempotency key for founding an organization, so "one founding per identity" was what that key bought, and the price was written down: no second organization through self-service.&lt;/p&gt;

&lt;p&gt;So I did not have a type problem. I had a founding-rule problem, and knowing that spared me a much bigger change.&lt;/p&gt;

&lt;h2&gt;
  
  
  The design: one identity, two linked organizations
&lt;/h2&gt;

&lt;p&gt;The decision keeps the enum as three mutually exclusive values and narrows the founding rule instead of deleting it: one self-service founding per identity per side. Illustrative SQL, simplified:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- Illustrative. Simplified from the design, not the production schema.&lt;/span&gt;
&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;organizations&lt;/span&gt;
  &lt;span class="k"&gt;ADD&lt;/span&gt; &lt;span class="k"&gt;CONSTRAINT&lt;/span&gt; &lt;span class="n"&gt;organizations_one_founding_per_side&lt;/span&gt;
  &lt;span class="k"&gt;UNIQUE&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;founder_user_id&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;type&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;A person can found one buyer organization and one supplier organization; a second buyer organization is refused. The idempotency key stays natural and stays in the database, not in a header the client sends.&lt;/p&gt;

&lt;h3&gt;
  
  
  Link, not merge
&lt;/h3&gt;

&lt;p&gt;I considered the obvious alternative: replace the type with capability flags like &lt;code&gt;can_buy&lt;/code&gt; and &lt;code&gt;can_sell&lt;/code&gt;. The ADR rejects it for two reasons.&lt;/p&gt;

&lt;p&gt;First, thirteen composite foreign keys pin each party column to an organization of the right type, so a supplier can never sit in a buyer's slot. Flags mean rebuilding that network in one change. Second, a shortcut like a fourth &lt;code&gt;BOTH&lt;/code&gt; type is worse: every &lt;code&gt;CHECK&lt;/code&gt; turns into &lt;code&gt;IN ('SUPPLIER','BOTH')&lt;/code&gt;, and the guarantee that one row is not both sides disappears without a constraint failing or a test going red.&lt;/p&gt;

&lt;p&gt;So the two organizations stay separate rows joined by a declared link. Verification does not cross it: a verified badge belongs to the supplier organization, and reviews are testimony about the supplier, not something the buying side inherits.&lt;/p&gt;

&lt;h3&gt;
  
  
  Block self-dealing
&lt;/h3&gt;

&lt;p&gt;Today an organization cannot invite itself as a supplier, because it is never both types. After that, a quote needs an invited recipient row, an award needs a quote, and a review is anchored to an award. The whole chain holds because the two types are disjoint on a single row.&lt;/p&gt;

&lt;p&gt;Give one person a row on each side and the chain protects nothing: the buyer row invites the supplier row, awards it, and rates it five stars. The design has to re-derive that protection explicitly:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight sql"&gt;&lt;code&gt;&lt;span class="c1"&gt;-- Illustrative. The shape of the constraint, not the exact production DDL.&lt;/span&gt;
&lt;span class="c1"&gt;-- Each row carries a denormalised copy of each party's link group,&lt;/span&gt;
&lt;span class="c1"&gt;-- held honest by a composite foreign key to organizations.&lt;/span&gt;
&lt;span class="k"&gt;ALTER&lt;/span&gt; &lt;span class="k"&gt;TABLE&lt;/span&gt; &lt;span class="n"&gt;rfq_recipients&lt;/span&gt;
  &lt;span class="k"&gt;ADD&lt;/span&gt; &lt;span class="k"&gt;CONSTRAINT&lt;/span&gt; &lt;span class="n"&gt;rfq_recipients_not_self_dealing&lt;/span&gt;
  &lt;span class="k"&gt;CHECK&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;buyer_link_group_id&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;supplier_link_group_id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;One detail changed between the sketch and the implementation. The sketch had a nullable link group with &lt;code&gt;IS NULL&lt;/code&gt; branches. But a PostgreSQL foreign key is &lt;code&gt;MATCH SIMPLE&lt;/code&gt; by default: if any referencing column is NULL, the constraint is satisfied without being checked. A writer that forgot the column would switch the rule off by omission, and nothing would report it. So an organization with no declared link is a group of one, its own id, and the check becomes a plain &lt;code&gt;&amp;lt;&amp;gt;&lt;/code&gt; over two &lt;code&gt;NOT NULL&lt;/code&gt; columns.&lt;/p&gt;

&lt;p&gt;The design writes its limits down too:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Only a declared link is caught. Two organizations created with two emails and no declaration pass, as they do today.&lt;/li&gt;
&lt;li&gt;Harvesting competitors' prices through your own legitimate request for quotation is market behaviour, not a schema problem. No key closes it, though the platform can at least see it once the link exists.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  The link must never widen a read
&lt;/h3&gt;

&lt;p&gt;Reads are scoped by the organization id the guard resolved from the membership. A supplier acting as a buyer is just a different buyer and gets the same not-found as anyone else. The link is presentational only: no query may use it to widen a tenant filter, and an architecture test fails the build if the column reaches a query condition, an ordering, an authorization path or a presenter.&lt;/p&gt;

&lt;h2&gt;
  
  
  Auth and sessions across subdomains
&lt;/h2&gt;

&lt;p&gt;One identity across several hostnames sounds like it needs shared cookies. It does not.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Each hostname is its own origin. &lt;code&gt;__Host-&lt;/code&gt; cookies carry no &lt;code&gt;Domain&lt;/code&gt; attribute, so a session on one surface is never shared with another, even by accident.&lt;/li&gt;
&lt;li&gt;Identity is shared through the issuer. Keycloak at &lt;code&gt;id.&lt;/code&gt; is the OIDC issuer, and external identities are keyed by &lt;code&gt;(issuer, subject)&lt;/code&gt;, so the issuer's hostname is a data-model boundary, not branding.&lt;/li&gt;
&lt;li&gt;Each application is an OIDC client with literal redirect and post-logout URLs. Wildcards are forbidden, so renaming a host is a two-place change, and the second place is the identity provider.&lt;/li&gt;
&lt;li&gt;Application session material lives in Redis behind an opaque cookie.&lt;/li&gt;
&lt;li&gt;The acting organization is chosen per request and verified against a membership. A header names it; the server decides whether the person may act as it. A client-sent "act as" role would be a worse design.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The cross-portal hop follows the usual OIDC pattern: the second application redirects to the issuer, the issuer already knows the person, and the person returns. I am describing that from the config and the ADRs, not from a recorded test. The design also calls for an explicit link between the buyer app and the supplier portal, with no silent switching, and every screen that changes something names the acting organization and its side.&lt;/p&gt;

&lt;h2&gt;
  
  
  If you already have duplicate accounts
&lt;/h2&gt;

&lt;p&gt;I have not run a merge of duplicate accounts in EgyGomla, and nothing here claims that. This is general guidance.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Count before you change anything.&lt;/strong&gt; The migrations in this repo count rows that violate a new rule and refuse to continue, naming them, instead of coercing or deleting them. Do the same for duplicates, using signals you trust: normalised email, phone, tax id, company name.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Never auto-merge on a match.&lt;/strong&gt; Similar details do not prove the same person, and a merge is hard to undo.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Let the person confirm both.&lt;/strong&gt; Ask them to sign in to each account, then attach both organizations to one identity and link them. Do not collapse them into one row.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keep catalogues and history where they are.&lt;/strong&gt; The link is for understanding, not for combining data.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Expand, backfill, contract.&lt;/strong&gt; Add nullable columns, backfill, then add constraints, and build unique indexes concurrently on a live database.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Ship writers first.&lt;/strong&gt; If a new column is &lt;code&gt;NOT NULL&lt;/code&gt; with no default, every writer, including seeds and scripts, must supply it before the migration runs.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Expect a tail.&lt;/strong&gt; Some people will never link. They behave as they do today, which is acceptable if the limit is written down.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What I'd do differently
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Start from the heaviest user's day.&lt;/strong&gt; Ask who the person is before deciding what each page needs, and walk through a day for the user who touches both sides.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Find where the constraint lives first.&lt;/strong&gt; I blamed the enum; the blocker was an onboarding rule I had chosen on purpose.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Write the abuse chain before the happy path.&lt;/strong&gt; The review system leaned on a property no constraint stated. Making it explicit was the most important part of the design.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Do not ship the second-organization path alone.&lt;/strong&gt; The ADR says it must not go out without the anti-self-dealing constraints, or self-dealing drops from "needs a second email" to "one click".&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Keep marketing behind the feature.&lt;/strong&gt; The ADR forbids copy like "one account buys and sells" until the feature exists, and a copy test guards the site's other promises.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Say what is decided and what is shipped.&lt;/strong&gt; This article describes a decision, not something in front of traders.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Mohamed Elgohary, Mobile &amp;amp; Product Engineer, Cairo. mohamedelgohary.dev&lt;/p&gt;




&lt;p&gt;&lt;em&gt;Originally published on my site: &lt;a href="https://mohamedelgohary.dev/writing/one-identity-many-roles-marketplace-accounts/" rel="noopener noreferrer"&gt;mohamedelgohary.dev&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

</description>
      <category>systemdesign</category>
      <category>architecture</category>
      <category>authentication</category>
      <category>postgres</category>
    </item>
  </channel>
</rss>
