Refresh families, relay locking, login throttling

You can isolate refresh-token sessions, coordinate concurrent outbox relays with FOR UPDATE SKIP LOCKED, and throttle login attempts per IP and email using Redis.

Learning outcomes

  • Explain how a refresh-token family detects replay and scopes revocation to one login.
  • Explain how Redis Lua scripts make refresh-token consumption and reuse detection atomic.
  • Explain how SELECT FOR UPDATE SKIP LOCKED coordinates concurrent outbox relays and why the relay checks Kafka before claiming rows.
  • Distinguish at-least-once delivery from exactly-once processing and explain the ordering trade-offs of parallel relays.
  • Explain how independent per-IP and normalised-email limits protect login requests, and how middleware preserves the request body.

A stolen refresh token can remain useful after its owner has rotated it. Two API instances can also select the same unsent outbox rows, while an instance that cannot reach Kafka can hold rows another instance could publish. Meanwhile, login attempts can target one account from many IP addresses or many accounts from one IP. You need separate controls for each problem without breaking the existing authentication, order or event flows.

Refresh-token families

A Refresh token lets a client obtain new access tokens without submitting its password again. During Refresh token rotation, the server consumes the presented refresh token and issues a replacement.

Deleting the consumed token creates a gap in your security model. Suppose a client holds token A, but an attacker copies it. The attacker submits A first, so the server consumes it and issues B. When the legitimate client submits A, the server rejects it because A no longer exists. The attacker can still use B.

A Refresh token family groups the refresh tokens descended from one successful login. Rotation keeps the replacement in the same family.

Each login starts a new family. A user who signs in on a laptop and a phone therefore has two independent families. Revoking one login should not invalidate the other.

Refresh token reuse detection identifies a request that presents a token already consumed by a successful rotation. The server needs to remember that the token was used, even though it can no longer authenticate with it.

One way to represent that evidence is a tombstone. It records the consumed token's family and remains available for the token's original remaining lifetime.

Consider this sequence:

  1. The client submits token A.
  2. The server consumes A and records its tombstone.
  3. The server issues token B in the same family.
  4. Someone submits A again.
  5. The server finds A's tombstone and identifies reuse.
  6. The server revokes the family's currently active token B.
  7. The server rejects the replay with HTTP 401.

The server cannot reliably tell whether the attacker or the legitimate client submitted A. Both must authenticate again after the family is revoked.

An unknown token is different from a consumed token. It has no active record and no tombstone, so the server must reject it without revoking any family.

Atomic refresh operations

The consume operation changes several related pieces of Redis state. It checks whether a token is active, consumes it, records its use and updates the family's current-token record.

These changes must happen atomically. Otherwise, two requests could both check token A before either consumes it. Both might then succeed and issue separate replacements.

A Redis Lua scripts runs its Redis commands as one atomic operation. No other Redis command can interleave with the script while it executes.

The script needs to distinguish three outcomes:

  • Active token: consume it, retain evidence of its use and allow rotation.
  • Consumed token: identify its family, revoke that family's current token and reject the request.
  • Unknown token: reject the request without changing any existing family.

The family record identifies the newest active token. When a consumed token is replayed, the server uses that record to revoke the right token, even if several rotations have happened since the original token was issued.

For example, consider a family that has rotated from A to B, then B to C, then C to D. Replaying A must revoke D, not only B. The tombstone for A must therefore retain the family identity, and the family record must continue to identify the current token.

Retention matters. If the server deletes A's tombstone immediately after consuming A, a later request cannot distinguish a replay from an unknown token. Keep the tombstone until the original refresh token's expiry.

The atomic operation also prevents two concurrent requests from consuming the same active token. One request can consume it; the other sees the consumed-token evidence and triggers reuse detection.

Concurrent outbox relays

Your order placement transaction writes an order, its order lines, its first order event and an outbox row together. The Transactional outbox lets a relay publish that event to Kafka after the database transaction commits.

A single relay can select unsent rows and publish them. Running multiple API instances means multiple relays may try to select from the same outbox table at the same time.

Without coordination, two relays can select the same unsent row and publish duplicate records. You need MySQL to reserve different rows for concurrent transactions.

Locking reads

A SELECT FOR UPDATE locking read acquires exclusive locks on the selected rows. Other transactions that need conflicting locks must wait until the first transaction commits or rolls back.

For example, a relay can select a small batch of unsent rows:

sql
SELECT id, topic, key_, payload
FROM outbox
WHERE sent_at IS NULL
ORDER BY id
LIMIT 5
FOR UPDATE;

If relay A locks rows 1 through 5, relay B's conflicting locking read cannot claim those rows while A holds the locks. Without another option, B waits.

Waiting wastes a relay's time when other unsent rows are available.

Skipping locked rows

MySQL's SKIP LOCKED changes that behaviour. A SKIP LOCKED locking read skips rows locked by another transaction instead of waiting for them.

sql
SELECT id, topic, key_, payload
FROM outbox
WHERE sent_at IS NULL
ORDER BY id
LIMIT 5
FOR UPDATE SKIP LOCKED;

If relay A has locked rows 1 through 5, relay B can skip them and claim the next available rows. Each relay can work on a different batch from the same table.

The result is not a consistent view of the entire table. It contains rows that were available to that locking read, excluding rows locked by competing transactions.

SKIP LOCKED does not mark rows as sent. It only changes which rows the locking read returns. Your relay still needs to publish the selected records and update their sent_at values.

Transaction isolation

The relay uses a database Transaction to coordinate its claim and sent-status update. For this workload, use the READ COMMITTED isolation level.

MySQL's default REPEATABLE READ isolation can introduce gap locks for locking reads. Those locks can interfere with new outbox inserts, including inserts made by order placement. READ COMMITTED avoids that gap-lock behaviour for this relay workload, so claiming pending rows does not unnecessarily block new outbox rows.

The transaction owns the row locks until it commits or rolls back. That means the order of operations matters.

A relay that cannot reach Kafka should not open a claim transaction and lock rows it cannot publish. Check broker connectivity first, using a short timeout. If the ping fails, return without claiming rows.

When Kafka is reachable, the relay's processing sequence is:

  1. Ping Kafka with a short timeout.
  2. Begin a READ COMMITTED transaction.
  3. Select unsent rows using FOR UPDATE SKIP LOCKED.
  4. Publish the selected records to Kafka.
  5. Update the selected rows' sent_at values.
  6. Commit the transaction.

Publishing and marking rows sent happen while the transaction still holds the selected row locks. If publishing or the database update fails, roll back. The rollback releases the locks and leaves the rows unsent for another relay.

A bounded batch limits how long a relay holds row locks while publishing. A large batch can keep locks open longer if Kafka is slow.

Delivery guarantees and ordering

The outbox transaction coordinates MySQL row state with a Kafka publish attempt, but MySQL and Kafka do not share one atomic commit.

Suppose Kafka accepts an event, then the relay crashes before MySQL commits the update to sent_at. MySQL still considers the row unsent. Another relay can select and publish it again.

This is At-least-once delivery delivery. Kafka may receive an event more than once, even though the relay marks the row sent after a successful publish. The outbox pattern prevents an event from being lost between the business transaction and publication, but it does not guarantee exactly-once delivery across both systems.

Consumers need idempotent handling of duplicate events. For example, the notifier can record processed event IDs and avoid applying the same event twice.

Parallel relays also affect ordering. Suppose relay A claims rows 1 through 5 and relay B claims rows 6 through 10. B might publish its batch before A publishes its batch. ORDER BY id controls selection order within each query, not publication order across relays.

Kafka preserves order within a partition. Using an order ID as the record key routes events for that order to the same partition. However, partitioning cannot fix an ordering mistake that happened before publication. If events for one order must remain in lifecycle order, they need a single ordered processing path.

Login throttling

Credential stuffing uses leaked email and password combinations to attempt logins against many accounts. An attacker may send attempts for many email addresses from a small number of IP addresses.

A different attack repeatedly targets one account while distributing requests across many IP addresses. An IP-only limit may not stop it.

You need two independent rate limiting dimensions on POST /v1/auth/login:

  • Client IP: limits login attempts originating from one network address.
  • Normalised email: limits attempts targeting one email identity.

The API configures these limits independently through LOGIN_LIMIT_PER_IP and LOGIN_LIMIT_PER_EMAIL. Both use the existing Redis fixed-window limiter with a one-minute window.

Each dimension needs a separate namespaced key. For example:

login-ip:203.0.113.10
login-email:user@example.com

The prefixes prevent the two login dimensions from sharing counters accidentally. They also keep login-specific keys separate from keys used by the global rate limiter.

A request is rejected when either applicable limit is exceeded. A request that passes the IP check can still exceed its email limit, and a request that passes its email check can still exceed its IP limit.

Trusted identity keys

An HTTP rate-limit identity key is the trusted identifier used to associate a request with a rate-limit bucket.

Use the connection address for the IP bucket. Do not use X-User-ID: an unauthenticated client can supply any value for that header, so it cannot establish the client's identity.

In Go, RemoteAddr usually contains a host and port. You can extract the host before building the IP key:

go
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
    host = r.RemoteAddr
}
ipKey := "login-ip:" + host

The email key comes from the login request body. Normalise it by trimming surrounding whitespace and converting letters to lowercase. Thus User@example.com, USER@example.com and User@example.com all use the same bucket.

When the application runs behind a reverse proxy, forwarded IP headers require care. Trust them only when the request comes from an explicitly trusted proxy. Otherwise, a client could forge the forwarded address and bypass the IP limit.

Middleware and request bodies

HTTP middleware wraps an HTTP handler so it can inspect a request before passing it to the next handler. Login-specific middleware can apply the IP limit and inspect the email before the authentication handler checks the credentials.

The request body is a stream. Reading it consumes the data, so the login handler would receive an empty body unless the middleware restores it.

In Go, you can read the bytes and replace the body with a new reader:

go
body, err := io.ReadAll(r.Body)
if err != nil {
    next.ServeHTTP(w, r)
    return
}
r.Body = io.NopCloser(bytes.NewReader(body))

The middleware can decode the email from the saved bytes. It should restore the body whether decoding succeeds or fails. If the body is malformed or does not contain a usable email, let the existing login handler produce its normal validation response.

The order of checks matters:

  1. Derive the IP from the connection address.
  2. Apply the IP limit before reading the body.
  3. Read the body and restore it for the next handler.
  4. Decode the email when possible.
  5. Normalise a usable email and apply its limit.
  6. Pass the restored request to the login handler.

The middleware should apply only to POST /v1/auth/login. Signup and refresh have their own behaviour, and the global limiter remains separate.

Rejection responses

When either login limit is exceeded, return HTTP 429 Too Many Requests with the error code rate_limited.

Include a Retry-After header with a non-empty value. It tells the client how long to wait before trying again. The value should reflect the remaining fixed-window interval rather than an arbitrary delay.

A rejected request should use the API's established JSON error format. The login handler should continue to own responses for invalid bodies and invalid credentials.

Email throttling also has a usability cost. An attacker can deliberately exhaust the allowance for another person's email address, temporarily preventing that person from logging in. Choose limits that accommodate normal mistakes and retries. Do not reveal whether an email exists through different rate-limit or authentication responses.

Hardening exercises

The three exercises apply these controls to the existing Go, MySQL, Redis and Kafka backend.

The refresh-token exercise checks that replaying a consumed token revokes the newest token in that login's family, while another login remains usable. It also checks that an unknown token revokes nothing.

The concurrent relay exercise runs multiple API instances against shared outbox rows. It checks that healthy relays publish every row without duplicates and that a relay with an unreachable broker leaves rows available to the healthy instance.

The login throttling exercise checks the independent IP and email limits, including forged X-User-ID values and differently cased or spaced email addresses. It also checks that middleware preserves the body so the login handler can still process valid credentials and reject malformed JSON.

Check your understanding

Question 1 of 4

A client successfully rotates token A into token B. Later, an attacker replays A. The family record identifies B as the current token. What should the server revoke?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (Redis Lua scripting, MySQL 8.4 InnoDB, Go 1.27 net/http).

Finished Lesson 3.21?