Skip to main content

Building a Realtime, Offline-Ready Kanban Board: Frontend System Design

Updated 14 min readMarkdown
Building a Realtime, Offline-Ready Kanban Board: Frontend System Design

Goal: Design a robust, scalable frontend system for a realtime Kanban board with first-class offline and real-time support.


1. Requirements & constraints

Functional

  • Create / read / update / delete: boards, lists, cards, comments, attachments.

  • Drag & drop cards between lists and reorder within a list.

  • Live updates: changes made by one user should appear near-instantly for others viewing the same board.

  • Offline support: users can continue to create, edit, and move cards while offline; changes sync when connectivity resumes.

  • Extended scope:

    • Real-time indication of who's online / editing

Non-functional

  • Low-latency UI (optimistic updates).

  • Should support both desktop and mobile devices. (PWA extended scope)

  • Websocket for real-time updates and HTTP REST for bulk operations.

  • Rendering: CSR instead of SSR since it will be easier to handle the complex scenarios around offline support and realtime updates. Also most of the benefits of SSR won’t be applicable here.

  • a11y with proper ARIA attributes and keyboard navigation support

  • i18n to support different locales and regions

  • Secure (auth, data rules), auditable with proper logs on who made changes

  • Monitoring and observability: Signoz (Opensource)

  • Mixpanel for product metrics


2. High-level architecture

Key pillars:

  • Sync Engine on the client orchestrates offline queue, transformation, and reconciliation.

  • Local Store mirrors a subset of backend (boards a user touches), enabling offline reads/writes.

  • Websocket server sends granular update events (card moved, card updated) so clients can patch local state instead of refetching full boards.


3. Client app — data model & components

Data model (simplified JSON)

Board {
  id: string,
  title: string,
  lists: string[], // list ids
  updatedAt: string,
  version: integer
}

List {
  id: string,
  title: string,
  cards: string[], // card ids
  updatedAt: string,
  version: integer
}

Card {
  id: string,
  title: string,
  description: string,
  attachments: [ { id, url } ],
  comments: [ { id, text, author, createdAt } ],
  orderKey: string, // fractional index / order token
  meta: { lastModifiedBy, lastModifiedAt }
}

Component structure (React)

  • Board - top-level container

  • ListColumn - renders header, CardList, and add-card control

  • CardList - List of cards (virtualize if needed)

  • CardItem - Single card item

  • DragLayer - DnD overlay

State management

  • Use a lightweight normalized store (Zustand or Redux Toolkit) with normalized entities boards, lists, cards to store the ephemeral client state.

    Normalized store

    
      {
        boards: { [boardId]: Board },
        lists: { [listId]: List },
        cards: { [cardId]: Card },
      }
    

Services

  • SyncEngine (singleton per logged-in user): interfaces with LocalStore and NetworkLayer, and syncs the offline state to server.

  • NetworkLayer: handles WebSocket & HTTP fetches, reconnection strategies, exponential backoff.

  • SWManager (Service Worker): asset caching, background sync attempts where possible.


4. Offline-first strategy

Goal: Users should still be able to work (create, edit, move cards) when the network is down, and the system will reconcile seamlessly once back online.

Key pillars: SyncEngine, Indexed DB and Service Worker(for background-sync)

Sync Engine

  1. Queue Operations SyncEngine.enqueue(op)

    Whenever a user performs an action (add card, move card, edit title), it:

    • Applies an optimistic update in the UI (Redux/Zustand)

    • Each UI mutation enqueues an operation with status as pending in IndexedDB.

      Client-sent ops include unique opId to let server deduplicate repeated delivery (Idempotency).

        {
          "opId": "uuid",
          "entityId": "card-123",
          "entityType": "card" | "list" | "board",
          "operationType": "create" | "update" | "move" | "delete",
          "payload": { "fromList": "todo", "toList": "done" },
          "status": "pending",
          "createdAt": "2025-10-04T01:30:00Z",
          "baseVersion": 23
        }
      
  2. Flush Queue (when online)

    • Tries sending all unsynced ops to the backend.

    • Waits for server ACKs.

    • On success → removes them from IndexedDB.

    • On failure → retries with exponential backoff.

    • Browser goes offline → Ops persisted in IndexedDB

  3. Conflict Resolution

    • If the server returns version conflicts (e.g., card already moved by another user),
      it merges using last-write-wins or CRDT(yjs) (if implemented).
  4. Real-Time Updates

    • Listens to WebSocket streams to receive updates from other users.

    • Updates the Redux/Zustand store accordingly.

Service worker

  • Background Sync (works even if the tab is closed)
    Registers a background sync task tagged sync-ops.

    • When the network is back, Service Worker’s sync event fires and calls SyncEngine.flushQueue()

    • Minimizes data loss risk.

    • Fallback: if background sync unsupported, flush is triggered on app resume based on browser’s online/offline event.

  • Cache API

    • Caches static assets (HTML, JS, CSS) for offline page loads.

    • Optionally caches REST data responses.

Reading data and UI feedback

  • When loading a board: load local snapshot from IndexedDB immediately; show loading state while fetching latest events from the server.

  • Server sync updates the local store incrementally.

  • Offline banner (You are offline, changes will sync automatically).

  • Queue indicator (e.g., "3 changes pending").


5. Real-time sync & conflict resolution

Goal: Ensure that multiple users can collaborate live on the same Kanban board with instant feedback, consistent state, and automatic conflict resolution when operations overlap.

Key pillars: WebSocker server and conflict resolution strategy

WebSocket Server

  • Each client connects to a board-specific WebSocket channel.

  • The server authenticates the connection (via token).

  • 🔼 Client → Server Communication

    The client primarily pushes intentions, describing what changed locally.
    The server treats these as proposed operations until they’re validated and sequenced.

    Flow:

    • User edits data offline or online → operation added to local queue.

    • On reconnect or flush trigger → client sends op data

    • Each op includes clientId, opId, baseVersion, and a compact delta. (mentioned above)

    • If opId already applied → reply ack (idempotent).

    • The server checks the baseVersion, if it’s still valid, the operation is accepted post conflict resolution and reconciles it with the current canonical state.

  • 🔽 Server → Client Communication

    The server pushes events that represent the canonical state after validation, sequencing, and conflict resolution.

    Flow:

    • Server validates client ops → applies conflict resolution (CRDTs, LWW, or ordering).

    • Generates a canonical event like card:created, card:updated, card:moved with new serverSeq.

        // event metadata
        {
          "type": "card:updated",
          "boardId": "board_42",
          "serverSeq": 12875,
          "entity": {
            "type": "card",
            "id": "card_123",
            "data": {
              "title": "Fix login bug",
              "listId": "list_A",
              "position": 2.5
            }
          },
          "delta": {
            "field": "title",
            "prev": "Login issue",
            "next": "Fix login bug"
          },
          "timestamp": "2025-10-04T18:22:15Z",
        }
      
    • Stores the event → broadcasts it to all connected clients of that board.

    • Clients patches the local store based on the event data and clear confirmed ops from queue.

End to end flow

Sample code for client side flow:

    // 1. User makes a change (optimistic update)
    const optimisticUpdate = {
      id: generateTempId(),
      ...changes,
      status: 'pending'
    };

    // Apply locally immediately
    updateLocalState(optimisticUpdate);

    // 2. Send to server via WebSocket
    socket.emit('card:update', {
      cardId,
      changes,
      version: currentVersion,
      boardId
    });

    // 3. Handle server response
    socket.on('card:update:success', (data) => {
      updateLocalState({ ...data, status: 'synced' });
    });

    // 4. Listen for updates from other users
    socket.on('card:updated', (update) => {
      if (update.userId !== currentUserId) {
        applyRemoteUpdate(update);
      }
    });

Sample code for server-side flow:

    // WebSocket handler
    io.on('connection', (socket) => {

      socket.on('board:join', async (boardId) => {
        socket.join(`board:${boardId}`);

        // Send current state
        const boardState = await getBoardState(boardId);
        socket.emit('board:state', boardState);
      });

      socket.on('card:update', async (data) => {
        try {
          // Validate and apply update
          const result = await updateCard(
            data.cardId,
            data.changes,
            data.version
          );

          // Broadcast to all clients in the board room
          io.to(`board:${data.boardId}`).emit('card:updated', {
            ...result,
            userId: socket.userId
          });

          // Confirm to sender
          socket.emit('card:update:success', result);
        } catch (error) {
            socket.emit('card:update:failed');
          }
        }
      });
    });

Conflict resolution strategies

Before we dive into the different resolution strategies, let’s first see how the server even identifies that there is a conflict. There are two fields, serverSeq and baseVersion which are absolutely central to maintaining consistency and conflict-free ordering.

serverSeq - Server Sequence Number

A global monotonically increasing number assigned by the server to every accepted operation/event on a board.

Helps clients know what they’ve already processed (lastSeenSeq). So if a client’s last seen sequence is 1533, it knows it needs events >1533.

baseVersion - Client’s Starting Point

The version number of the board (or entity) that the change was based on. Let’s the server detect if the client’s view was stale when it submitted the operation.


How server detects conflicts?

Load current entity and its entityVersion (or canonical representation / CRDT doc).

Compare versions

  • If op.baseVersion == entityVersion: no version gap → no conflict in principle — apply op.

  • If op.baseVersion > entityVersion: client claims a future state → treat as error (bad client state).

  • If op.baseVersion < entityVersion: there have been intervening ops → potential conflict.

Strategies

  • Last-Write-Wins (LWW)

    Simplest approach. The update that arrives at the last based on timestamp or serverSeq completely overwrites any previous update.

    • Easy to implement

    • Suitable for non-critical fields like card titles, where precision is less critical and conflicts are rare

    • Silent data loss

    • No user awareness of conflict

  • CRDTs (Conflict-free Replicated Data Types)

    Special data structures that are mathematically designed to merge automatically, no matter what order changes arrive in the merge is deterministic and conflict-free.

    • Libraries like Yjs are available, which is a battle-tested implementation of CRDT

    • Suitable for fields where multiple concurrent edits are frequent, like labels, descriptions, etc.

    • Works well with offline clients.

    • Types of CRDTs:

      • LWW-element-set: last-write-wins for tags or labels.

      • Sequence CRDT / Ordered list: maintains order of elements (e.g., card positions).

      • Counter CRDT: for increment-only counters.

“Won’t be diving into the depth of each of these since CRDT is a vast topic in itself.”

  • Operational Transform (OT) / Server-side Arbitration

    The server decides how concurrent operations are applied to the canonical state of an entity. Clients submit operations, but the server determines the order, merges, or rejects them and returns a canonical state with serverSeq + resolvedDelta. Client uses that to reconcile the local op state.

    • Useful for structural or destructive operations (like moving cards, deleting cards) where the merging logic is complex or custom.

Hybrid approach

Operation TypeRecommendedReason
Card moves / reorderFractional indexing + OTStructural ops need deterministic ordering
Card deleteTombstone + OTPrevent resurrected edits
Card title / simple fieldsLWWLow-risk fields; last-write-wins is acceptable
Card description / rich-text editsCRDTMultiple concurrent edits; automatic merge
CommentsCRDT append-onlyConcurrent-safe, no merge conflicts
Labels / tagsLWW-element-set CRDTConcurrent add/remove without loss

6. APIs

REST APIs

Used for initialization, authentication, batch operations, rare updates (non real-time).

Authentication

  • POST /login → returns JWT or session token

  • POST /logout → invalidate token

  • GET /user → get user info

Board Management

  • GET /boards → list all boards the user has access to

  • GET /boards/:id → fetch board details (columns, cards, users)

  • POST /boards → create a new board

  • DELETE /boards/:id → delete a board

Column/List Management (initial load)

  • GET /boards/:id/columns → get all lists or columns in a board

Card Management (initial load)

  • GET /columns/:id/cards → fetch cards in a column

WebSocket

Used for all board/card/column operations that should propagate immediately to other users:

Card Operations

  • card:create → create a new card

  • card:update → update title, description, labels, assignees

  • card:move → change column or position

  • card:delete → remove card

  • card:comment:add → append comment

Column Operations

  • column:create → create a column

  • column:update → rename a column

  • column:move → reorder columns

  • column:delete → remove column

Board Operations

  • board:update → update board metadata (e.g., title)

  • board:share → add/remove collaborators

System / Meta Operations

  • sync:request → client asks for missed events after reconnect (using lastSeenSeq)

  • ack → server confirms op applied with serverSeq

  • op:rejected → server rejects an operation (conflict, validation failure)

  • board:event → server broadcasts canonical events (any changes)

Error code reference

CodeHTTP StatusMeaning
VERSION_CONFLICT409Update failed due to conflict
NOT_FOUND404Entity doesn't exist
PERMISSION_DENIED403No access rights
INVALID_OPERATION400Malformed request
RATE_LIMIT_EXCEEDED429Too many requests
VERSION_TOO_OLD409Client state too stale
CARD_DELETED410Operating on a deleted card
SERVER_ERROR500Internal error

7. Client-side performance

  • Virtualize long lists: Use libraries like react-window or react-virtualized to efficiently render thousands of cards without DOM performance issues.

  • Debounce expensive operations: For actions like autosave or heavy computations, debounce or throttle updates to reduce unnecessary work.

  • Incremental updates: Apply server-sent patches or deltas instead of re-fetching the full board, minimizing network load and UI re-renders.

  • Lazy loading media: For cards with attachments or images, load content lazily as users scroll into view.

  • Efficient data structures: Maintain normalized state (e.g., separate cards, columns, and board entities) to minimize deep object copies and state updates.


8. Security and privacy

Authorization and Access Control

  • Server-side authorization: Always verify that the user has permission for every operation, including creating, updating, or deleting boards, columns, and cards.

  • Role-based access control (RBAC): Define roles such as admin, editor, or viewer, and enforce permissions consistently across the API and WebSocket events.

Data in Transit and Storage

  • Encrypt all traffic: Use HTTPS / WSS to protect data in transit.

  • Secure attachments: Use signed URLs with expiry for file uploads/downloads to prevent unauthorized access.

  • Encrypt sensitive data at rest where applicable (e.g., user credentials, API tokens).

Input Validation and Sanitization

  • Sanitize user input: Protect against XSS in card titles, descriptions, and comments by using a robust markdown or HTML sanitizer.

  • Limit payload sizes: Prevent denial-of-service attacks from overly large fields.

Web Security Best Practices

  • CSRF Protection: Even with WebSockets, protect any REST endpoints from cross-site request forgery by using CSRF tokens or double-submit cookies.

  • CSP (Content Security Policy): Define a strict CSP to prevent injection attacks and reduce XSS risks, especially for rich text or markdown content.

  • CORS (Cross-Origin Resource Sharing): Restrict API access to trusted origins and enforce proper headers to prevent unauthorized cross-origin requests.

  • Rate limiting and abuse prevention: Limit the number of operations per client or per IP to avoid brute-force or spam attacks.

Additional Measures

  • Audit and logging: Log security-relevant actions, including failed authorization attempts, suspicious patterns, and admin actions.

  • Token expiration and rotation: Ensure authentication tokens (JWTs or session tokens) expire appropriately and rotate secrets regularly.

  • Offline data security: Encrypt local storage if caching sensitive data or offline operations on the client.


9. Failure scenarios & recovery patterns

Duplicate Operation Delivery

  • Cause: Network retransmits, client crash and retry, or retry logic triggered multiple times.

  • Mitigation:

    • Server-side deduplication: Use opId to detect and ignore duplicate operations.

    • Client acknowledgement tracking: Mark ops as acknowledged once the server confirms (op:ack) to avoid re-sending unnecessarily.

    • Idempotent operations: Design operations to be safe when applied multiple times if deduplication fails.


Out-of-Order Events

  • Cause: Network reordering, multiple WebSocket hubs, or event propagation delays.

  • Mitigation:

    • Sequence tracking: Attach a monotonically increasing serverSeq to each event.

    • Resync on reconnect: Use lastSeenSeq to request any missed events from the server, ensuring a consistent state.


Attachment Upload Failures

  • Cause: Network interruptions, client crash, or server errors during file upload.

  • Mitigation:

    • Persist upload state locally: Use IndexedDB or LocalStorage to track in-progress uploads.

    • Retry with exponential backoff: Attempt resumable uploads if supported; otherwise, retry as a new upload.

    • Deduplication on server: Use content hash or metadata to prevent duplicate attachments if the upload restarts.


Offline & Reconnection Handling

  • Cause: Client loses network or closes app mid-operation.

  • Mitigation:

    • Queue operations locally: Maintain an offline queue with opId and baseVersion.

    • Send queued ops in order: On reconnect, replay ops via WebSocket and reconcile with canonical server state.


10. References

About the author

  • UI Engineer currently simplifying the process of building generative AI bots @yellow.ai. On a journey to make the web a better place by building engaging and performant UIs.

Good tutorial 👍🏼

1