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.
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.
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.
Delay the irreversible step
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.
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:
- push notifications to the recipient,
- webhooks and analytics events such as
message_sent, - search indexing and "last activity" timestamps.
If your analytics fires on tap, your dashboard will count sends that were cancelled. Fire it when the state machine reaches SENT, not before.
Keep the window short and explicit
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.
Two things make a window usable:
- It is visible. A pending state with a clear Undo control, and ideally the remaining time, so nobody wonders whether the thing happened.
- 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.
Model it as a state machine with one atomic gate
There are four states: PENDING, SENDING, SENT and CANCELLED. 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:
// Do not do this: another coroutine can run between the read and the write.
if (item.state == SendState.PENDING) cancel(item)
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 UPDATE does that, and the number of affected rows tells you who won:
enum class SendState { PENDING, SENDING, SENT, CANCELLED }
@Entity(tableName = "outbox")
data class OutboxItem(
@PrimaryKey val id: String, // doubles as the idempotency key
val payload: String,
val state: SendState,
val sendAtMillis: Long, // wall-clock deadline, persisted
)
@Dao
interface OutboxDao {
@Insert
suspend fun insert(item: OutboxItem)
@Query("UPDATE outbox SET state = 'CANCELLED' WHERE id = :id AND state = 'PENDING'")
suspend fun cancelIfPending(id: String): Int
@Query("UPDATE outbox SET state = 'SENDING' WHERE id = :id AND state = 'PENDING'")
suspend fun claimIfPending(id: String): Int
@Query("UPDATE outbox SET state = 'SENT' WHERE id = :id AND state = 'SENDING'")
suspend fun markSent(id: String): Int
@Query("SELECT * FROM outbox WHERE state IN ('PENDING', 'SENDING')")
suspend fun unfinished(): List<OutboxItem>
}
If cancelIfPending 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.
SENDING 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.
Persist the pending action
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:
class UndoableSender(
private val dao: OutboxDao,
private val api: MailApi,
private val scope: CoroutineScope,
private val now: () -> Long = System::currentTimeMillis,
) {
suspend fun submit(payload: String, windowMillis: Long): String {
val item = OutboxItem(
id = UUID.randomUUID().toString(),
payload = payload,
state = SendState.PENDING,
sendAtMillis = now() + windowMillis,
)
dao.insert(item) // persisted before anything else
scope.launch { deliver(item) }
return item.id
}
suspend fun undo(id: String): Boolean = dao.cancelIfPending(id) == 1
suspend fun resumeAfterRestart() {
dao.unfinished().forEach { item -> scope.launch { deliver(item) } }
}
private suspend fun deliver(item: OutboxItem) {
if (item.state == SendState.PENDING) {
delay((item.sendAtMillis - now()).coerceAtLeast(0))
if (dao.claimIfPending(item.id) == 0) return // undone, or another driver won
}
api.send(item.payload, idempotencyKey = item.id)
dao.markSent(item.id)
}
}
After a restart, resumeAfterRestart 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.
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 claimIfPending is atomic, so whichever arrives second gets 0 rows and does nothing.
Give every send an idempotency key
Look at the last two lines of deliver. If the process dies after api.send succeeds but before markSent runs, the item is still SENDING 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.
The outbox row's id is the idempotency key, generated once, before anything is sent, and reused on every retry. The server enforces it:
-- Server side: the key is scoped to the sender and enforced by the database.
CREATE TABLE messages (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sender_id bigint NOT NULL,
idempotency_key text NOT NULL,
body text NOT NULL,
UNIQUE (sender_id, idempotency_key)
);
INSERT INTO messages (sender_id, idempotency_key, body)
VALUES ($1, $2, $3)
ON CONFLICT (sender_id, idempotency_key) DO NOTHING
RETURNING id;
If RETURNING 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.
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 FAILED state that the person can see, or it sits in SENDING 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.
Keep Undo reachable
A beautifully atomic state machine is useless if the Undo control is gone when someone reaches for it. The common ways to break it:
- the toast is owned by a screen, and navigating away dismisses it,
- it renders behind the keyboard or the system bars,
- it disappears on its own timer while the pending window is still open.
On the last one: in Compose, SnackbarDuration.Short and Long are fixed durations, not your window. Use Indefinite and drive the dismissal from the deadline:
suspend fun showUndo(
host: SnackbarHostState,
sender: UndoableSender,
id: String,
windowMillis: Long,
) {
coroutineScope {
val timer = launch {
delay(windowMillis)
host.currentSnackbarData?.dismiss()
}
val result = host.showSnackbar(
message = "Message sent",
actionLabel = "Undo",
duration = SnackbarDuration.Indefinite,
)
timer.cancel()
if (result == SnackbarResult.ActionPerformed && !sender.undo(id)) {
host.showSnackbar("Too late, it was already sent")
}
}
}
Host the SnackbarHostState 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.
Prefer undo over "Are you sure?"
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.
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.
There's a 34-second Arabic version of this in my «خلف الكواليس» series: https://youtube.com/shorts/_fdEGjdvbks
Top comments (16)
The framing that Undo Send is a delay, not an undo, really landed for me — once a message reaches someone else's mailbox there is nothing to recall. I liked the atomic gate most: cancelIfPending returning 1 means Undo won and the send will never happen, and 0 means the timer won, with no race between the read and the write. The SENDING state also makes sense as the stretch where Undo is no longer possible but the server has not confirmed yet. The SnackbarDuration.Indefinite point was new to me too — Short and Long are fixed, so they cannot match a 5, 10, 20 or 30 second window. When you picked the default window for a chat app, did you lean toward 5 seconds for speed, or longer because people notice a mistake right after tapping send?
Thanks, Abdullah! For a normal chat app I would not hold every message, because even five seconds feels broken there. I keep the window for actions that are hard to undo, and people should be able to pick a longer time.
Five seconds is a fine default. Would you make it per account, or keep one number for everyone?
For a small local action I went with compensate instead of delay. Tapping an amount habit, like water, adds the step right away and shows a bar with Undo. Only one offer exists at a time, a new tap replaces it.
And if the server refuses the add, the Undo offer gets pulled too. Otherwise Undo takes a step off a total that never went up.
Nice approach, and pulling the Undo offer when the server rejects the add is the part most people miss. Thanks for sharing it!
The CAS transitions in
OutboxDao(WHERE id = :id AND state = 'PENDING') plus firingmessage_sentonly after reachingSENTshould honestly be mandatory reading for anyone building mobile actions with real-world side effects.One subtle Android wrinkle we ran into with persisted
sendAtMillis: if the device clock jumps while the undo window is open (NTP sync coming out of airplane mode or manual clock change), wall-clockSystem.currentTimeMillis()can either fire the irreversible step early or hold it way too long. Pairing persisted(createdAtWallMillis, windowDurationMs)with monotonicSystemClock.elapsedRealtime()while the process is alive — and only falling back to wall-clock across process death — saved us from some nasty edge cases.Thank you! You are right about the clock jump. The code in the article only uses the wall clock, so your mix of elapsedRealtime and wall clock after process death is the safer way.
Persisting sendAtMillis is what makes the after-restart path clean. The one edge I'd test is the device clock moving: if the user or the network time sync jumps the wall clock forward, pending items send early, and a jump backwards holds them longer than the window. Keeping an elapsedRealtime deadline for the in-process timer and only falling back to the wall clock after a reboot avoids both.
Good catch, thanks. A clock change can send the message early or hold it too long. Your fix is better than my code: elapsedRealtime while the app runs, and the wall clock only after a reboot.
analytics fires on SENT, not on tap. a cancelled send would otherwise count as sent.
Good point. Counting on tap would log sends that never happened, so the event belongs on the real send, after the undo window closes.
After the undo window closes. Anything earlier counts sends that never happened.
Exactly. Thanks, Odinaka!
Seen as an alternative to another « are you sure? » invite it makes so much sense!
Exactly, people click through confirmations out of habit, but they notice a mistake right after the action. Thanks for reading, Dominique!
Delaying the irreversible step is a rule that travels well beyond email. Firing analytics on SENT rather than on tap is the part teams usually discover from a confusing dashboard.
We used the same idea in CleanSync, a tool Ascendra Ventures built to keep Google Drive and Gmail on your own server. The question we kept returning to was not storage but trust: can a sync job move your files without ever quietly deleting one? Every sync is rehearsed first, and if it would delete more files than your limit, it stops and shows the list. Anything replaced or deleted goes to a Recovery folder first. Mail rules written in plain words suggest before they act, and every change can be undone. Your cancel versus compensate distinction maps closely onto that: the rehearsal is the delay, and the Recovery folder is the compensation for whatever still slips through.
Underneath it all sits one question, what is the system allowed to do without a human? How do you choose the window length when the same action is sometimes trivial and sometimes destructive, for example one deleted record against a bulk delete?