Per-user Redis replay log

You build a Redis replay log that accepts user-scoped payloads and returns increasing IDs plus retained entries after a supplied ID. Concurrent appends must receive distinct IDs.

Ticket

Build a per-user event log in Redis in backend/internal/replay. Append stores a payload and returns its event ID. Since returns retained entries with IDs greater than a supplied ID, in ascending order.

The package exposes this API:

go
type Entry struct {
	ID      int64
	Payload []byte
}

func NewLog(rdb *redis.Client, maxLen int64, ttl time.Duration) *Log
func (l *Log) Append(ctx context.Context, userID int64, payload []byte) (int64, error)
func (l *Log) Since(ctx context.Context, userID int64, afterID int64) ([]Entry, error)

The tests call these declarations directly. They carry the w5o1 build tag, which make test W=5O1 adds automatically.

The phone can lose its WebSocket connection while Redis pub/sub continues delivering live events to connected clients. Your Reconnecting WebSocket flow needs a way to recover events published during that gap. Keep Pub/sub fan-out across instances for live delivery and use the replay log to fill the gap. Replayed messages provide At-least-once delivery delivery, so a client may receive an event again if it reconnects before updating its last-seen ID.

This is an optional extension, not an HTTP endpoint. Use Go context for Redis operations and Redis TTL to expire inactive users' logs. The existing Redis pub/sub path remains responsible for live events.

Acceptance criteria

  • The first three appends for one user return IDs 1, 2 and 3.
  • After appending payloads a, b, c and d, Since(userID, 2) returns exactly two entries in ascending order: ID 3 with payload c, followed by ID 4 with payload d.
  • After appending two events, Since(userID, 0) returns both retained entries.
  • Calling Since for a user with no entries returns an empty slice and no error.
  • With maxLen set to 3, five appends leave only entries with IDs 3 through 5.
  • With a configured TTL of 90s, every Redis key belonging to the user has a TTL greater than zero and no greater than 90s after an append.
  • Fifty concurrent appends for one user receive 50 distinct IDs.
  • A different user cannot see the first user's entries, and their first appended event receives ID 1.

Constraints

  • Use one sequence key and one entries key per user.
  • Allocate IDs with an atomic Redis increment so concurrent appends never receive duplicate IDs.
  • Keep only the newest maxLen entries in the sorted set.
  • Set the configured TTL on every key written by the log.
  • Allocate the ID with the increment first, then perform the entry insertion, trimming and expiry updates on both keys together in one pipeline or transaction.
  • Do not add an HTTP endpoint. This exercise only builds the replay package.

Design direction

Keep the implementation in internal/replay. Let the package own the Redis key naming, ID allocation, entry encoding and replay queries. Use a per-user sequence key with Redis INCR and a separate per-user sorted set for entries. The event ID belongs in the sorted set score so Redis can order entries by ID.

Consider how you encode each sorted set member. It must preserve the event ID and exact payload bytes while remaining unique for each entry. Keep the encoding and decoding rules symmetric.

The append boundary needs to coordinate ID allocation, insertion, trimming and expiry updates. Consider a Redis transaction or script so these operations stay together while the generated ID is available for the member. A sorted set makes range queries and trimming straightforward, but you still need to decide how to remove the oldest entries without deleting the newest ones.

Pass the supplied context to Redis operations and return Redis errors to the caller. Any package layout that meets the contract passes. You can choose the internal key names and encoding format.

How to check your work

Run the optional exercise tests from the repository root:

bash
cd backend && TEST_REDIS_ADDR=127.0.0.1:6379 make test W=5O1

Read the first failing assertion carefully. Compare the actual ID, returned order, payload, retained entry count or TTL with the expected value to identify which part of the contract your implementation has not met.

Finished Exercise 5.15?

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. Append returns increasing per-user IDs starting at 1.
  2. Since returns only newer entries in ascending order with their original payloads.
  3. Unknown users receive an empty result without an error.
  4. The log retains only the newest maxLen entries and refreshes every written key's TTL.
  5. Fifty concurrent appends receive unique IDs, and different users have separate logs.

Commands

terminal
cd backend && TEST_REDIS_ADDR=127.0.0.1:6379 make test W=5O1

Tests

  • TestW5O1_AppendReturnsIncreasingIDsStartingAtOne in backend/internal/replay/log_test.go
  • TestW5O1_SinceReturnsOnlyNewerEntriesInOrder in backend/internal/replay/log_test.go
  • TestW5O1_SinceZeroReturnsEverythingKept in backend/internal/replay/log_test.go
  • TestW5O1_SinceForAnUnknownUserIsEmpty in backend/internal/replay/log_test.go
  • TestW5O1_OnlyTheNewestEntriesAreKept in backend/internal/replay/log_test.go
  • TestW5O1_EveryKeyExpires in backend/internal/replay/log_test.go
  • TestW5O1_ConcurrentAppendsGetUniqueIDs in backend/internal/replay/log_test.go
  • TestW5O1_UsersHaveSeparateLogs in backend/internal/replay/log_test.go