DEV Community

Mohamed Elgohary
Mohamed Elgohary

Posted on

Undo Send is a delay, not an undo

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:

  1. It is visible. A pending state with a clear Undo control, and ideally the remaining time, so nobody wonders whether the thing happened.
  2. 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)
Enter fullscreen mode Exit fullscreen mode

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>
}
Enter fullscreen mode Exit fullscreen mode

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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 (0)