Kanban Board — Front-End System Design for a Trello-Style Project Management Board
A deep dive into building a Trello-style kanban board — from drag-and-drop columns and card CRUD to optimistic updates, WebSocket real-time sync, and offline mutation queues.
FrontendX EngineeringSystem Design Series
1. Requirements & Scoping
A kanban board looks simple: four columns with cards you drag between them. Trello, Jira, Asana, and Microsoft Planner all follow this pattern. But add real-time collaboration, offline support, and a rich card model with labels, due dates, attachments, and comments, and the architecture becomes surprisingly deep.
The core tension is between responsiveness and consistency. The user drags a card and expects it to land instantly in the new column — but the server must validate, persist, and broadcast the move to every other connected client. Every component has to be designed around this split-second gap between local and remote state.
Key Insight
This question appears frequently in frontend interviews at JioCinema, Apple, and Atlassian. The range goes from SDE1 (basic drag-drop and CRUD) to Staff (offline sync, conflict resolution, and real-time collaboration architecture).
Functional
Four swimlanes: To Do, In Progress, In Review, Done
Drag-and-drop cards between columns using dnd-kit
CRUD: create, read, update, delete cards with title, description, labels, due dates
Labels and priority tags per card
Assign cards to team members
Real-time sync via WebSocket — all peers see changes instantly
Offline mutations queued and replayed on reconnect
Non-Functional
Performance: 60fps drag animations with 200+ cards visible
Offline resilience: queued mutations survive tab close
Conflict resolution: last-write-wins with server authority
Accessibility: full keyboard navigation, ARIA roles, screen-reader announcements
Bundle: drag-drop engine under 15KB gzipped
Tip
Start from the drag-drop interaction model. Every other feature — optimistic updates, WebSocket events, offline queue — exists to make dragging feel instant and reliable. If the drag-drop is not smooth, nothing else matters.
2. Component Architecture & API
The kanban board splits into a small component hierarchy.KanbanProvider owns the Zustand store and WebSocket connection. KanbanBoard wraps the DndContext and renders fourKanbanColumn components. Each column renders its cards via a SortableContext. A DragOverlay shows the card being dragged. CardDetail opens as a modal for create and edit operations.
The provider stays at the top because multiple boards or a board + sidebar view may need shared state. Keeping the WebSocket connection and mutation queue at the provider level prevents duplicate connections and ensures all child components receive remote events.
Component hierarchy — KanbanProvider holds state and WebSocket connection; KanbanBoard renders columns; each column holds cards; CardDetail opens as a modal for create/edit.Kanban board with four swimlanes — cards can be dragged between columns with optimistic local updates and WebSocket sync
Note
Each column is a drop target, each card is a sortable item. TheclosestCorners collision detection strategy works best because cards tend to stack vertically and the user drags horizontally across columns.
3. Data Model / State Shape
The client state is normalized: tasks live in a flat Record<string, Task>, columns reference their card order via taskIds: string[]. This makes moving a card between columns a constant-time operation — pop the id from one array, push to another — without ever touching the task objects themselves.
I keep a separate pendingMutations queue for offline changes. Each mutation carries a client-generated idempotency key so the server can deduplicate in-flight requests after a reconnect.
Normalizing by column-taskIds rather than embedding status on the task object is deliberate. It makes drag-drop a pure array operation, avoids iterating all tasks to find which column a task belongs to, and keeps the column ordering independent of task data.
4. Interface Definition (API)
The API has two planes: a REST API for CRUD operations and a WebSocket channel for real-time broadcast. The REST API follows conventional patterns — fetch the board, then create, update, move, or delete tasks. The WebSocket channel broadcasts every mutation to all connected clients so the board stays in sync without polling.
Every mutation from the client includes a mutationId — a UUID the client generates. The server tracks processed mutation IDs and ignores duplicates. This is essential for offline replay: if the client sends a mutation, loses the connection, then reconnects and sends it again, the server does not apply it twice.
Never rely on WebSocket delivery order for correctness. The server should broadcast the canonical state after every mutation, and the client should apply events idempotently. A reconnect always triggers a full board sync (via REST) before listening to new WebSocket events.
5. Component Deep Dive
Three pieces deserve close attention: the drag-drop integration with dnd-kit, the optimistic update pipeline, and the offline mutation queue. Everything else in the kanban board is conventional UI work.
Drag-and-Drop with dnd-kit
dnd-kit is the de facto standard for drag-and-drop in React. It gives us DndContext, collision detection strategies, sortable presets, and a DragOverlay for custom drag previews. The PointerSensor uses an activationConstraint of 8px so a click does not accidentally trigger a drag.
Columns are droppable containers; cards are sortable items. When a drag ends, we detect which column the card originated from and which column it landed in. If they differ, we optimistically move the card in local state and flush the mutation to the server.
Use closestCorners collision detection, not closestCenter. Cards are tall and narrow; the corner strategy correctly identifies which column the card is entering based on its top-left corner rather than its center, which matters when columns are narrow on mobile.
Optimistic Updates
Every mutation follows the same pattern: apply the change to local state immediately, send the request to the server, and reconcile when the server responds. If the server confirms, we update local state with the canonical payload. If it fails, we roll back and optionally enqueue the mutation for retry.
The rollback stores a snapshot of the affected task right before the optimistic mutation. On failure, we restore the snapshot. This is simpler than computing inverse operations and works for any mutation type.
example.tsx
import { useShallow } from "zustand/react/shallow";
import { useKanbanStore } from "./kanban-store";
function useOptimisticMove() {
const { tasks, columns, applyMutation, enqueuePending } = useKanbanStore(
useShallow((s) => ({
tasks: s.tasks,
columns: s.columns,
applyMutation: s.applyMutation,
enqueuePending: s.enqueuePending,
})),
);
return useCallback(
async (taskId: string, toStatus: string, order: number) => {
const mutation = {
id: crypto.randomUUID(),
type: "task:moved" as const,
payload: { taskId, toStatus, order },
timestamp: Date.now(),
};
// 1. Apply optimistically
applyMutation(mutation);
try {
// 2. Flush to REST API
const res = await fetch(`/api/tasks/${taskId}/move`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ status: toStatus, order }),
});
if (!res.ok) throw new Error("Sync failed");
// 3. Confirm — server returned canonical data
const serverTask = await res.json();
applyMutation({
type: "task:updated",
payload: serverTask,
timestamp: Date.now(),
});
} catch {
// 4. Rollback on failure
applyMutation({
type: "task:rollback",
payload: { mutationId: mutation.id },
timestamp: Date.now(),
});
enqueuePending(mutation); // retry later
}
},
[tasks, columns, applyMutation, enqueuePending],
);
}
Warning
A common pitfall: optimistic updates that do not account for reorder within a column. When a card moves to position 5 of a 10-card column, the server must update the order field of every card between the old and new position. The optimistic local update must do the same or the order snaps back on server reply. Always batch the local reorder with the remote move.
6. Data Flow & Communication
The data flow has three modes: online (REST + WebSocket), offline (local mutations queued), and reconnecting (flush queue then full sync). The Zustand store backed by persist middleware saves the board state and pending mutations to localStorage so even a tab close does not lose offline work.
User actions optimistically update local state, then flush to the REST API. The server broadcasts via WebSocket so all peers converge.
WebSocket Reconnect with Backoff
The WebSocket connection uses exponential backoff: 1s, 2s, 4s, up to 30s. On reconnect, we immediately flush any pending mutations from the offline queue, then request a full board sync via REST to converge with the server state. Any events received via WebSocket during the flush are applied idempotently via the mutation ID.
When the browser detects it is offline (via navigator.onLine and the offline event), every mutation is queued into pendingMutations in Zustand, which is persisted to localStorage. The queue stores the mutation type, payload, timestamp, and retry count. When the connection returns, the queue is flushed sequentially.
Each queued mutation carries a client-generated UUID as its idempotency key. The server stores processed IDs in a bounded cache (e.g., last 1000) and replies with the cached response if a duplicate arrives. This prevents duplicate card creation or double-moves when the client retries after a timeout.
Offline mutations are queued locally and replayed when connectivity returns, with idempotency keys to prevent duplicate processing.
Key Insight
Trello famously solved the offline dual-ID problem by maintaining a map of client-generated task IDs to server IDs. When a task is created offline, it gets a client UUID. On sync, the server assigns its own ID and returns it. The client updates its map and replaces references everywhere. This is why everytask:created mutation includes the client ID — the server can correlate them.
7. Performance Optimization
A kanban board can easily hold hundreds of cards across four columns. Without care, every drag or reorder re-renders every card. The key strategies are column-level memoization, stable keys, and limiting the scope of drag updates.
Column-Level Memoization
Each column is a memoized component that only re-renders when its taskIds array reference changes. Individual cards are also memoized — they only re-render when their own task data changes. This means a move between columns only triggers a re-render in the source and destination columns, not in all four.
Stable Identifiers
Every card uses its server-assigned id as the React key. Draft cards created offline get a temporary client UUID that is replaced with the server ID on sync. We never use array indices as keys — they cause every card to remount when the list reorders.
Virtualized Columns
When a column grows beyond ~50 cards, we virtualize it. The column measures its height and only renders cards within the viewport plus a buffer. The container maintains the full scroll height so the browser scrollbar stays accurate. Virtualization integrates with dnd-kit via the useVirtualizer adapter.
Bundle Splitting
dnd-kit is large (~12KB gzipped). The CardDetail modal with its rich text editor is another ~8KB. Both are lazy-loaded via dynamic import. The initial load only includes the kanban board shell, Zustand store, and the first column of card data.
Tip
Profile drag performance with the React DevTools profiler. Each drag cycle should re-render at most two columns and oneDragOverlay. If all four columns re-render, check your selectors — odds are a parent component is passing new object references on every render.
Approach
Pros
Cons
Re-render everything on drag
Simple to implement, no memoization needed
Jank above 50 cards; all columns re-render on every pixel of drag
Column-level memoization with shallow compare
Only source and destination columns re-render; smooth up to 200 cards
Managing reference equality requires discipline in selectors
Virtualized columns + memoized cards
Handles 1000+ cards per column; DOM stays under 100 nodes
A kanban board is a collaborative workspace. Authorization, input sanitization, and WebSocket origin checks are the primary security concerns.
Authorization per Board
Every REST endpoint and WebSocket message must verify the user belongs to the board. Board membership is checked on every request — not just on initial load. If a user is removed from a board, their WebSocket connection should be terminated server- side.
XSS in Card Content
Card titles, descriptions, and comments may contain HTML. Sanitize all user-generated content with DOMPurify before rendering. Never pass raw content to dangerouslySetInnerHTML. A stored XSS in a kanban card description can exfiltrate board data or perform actions as the victim.
WebSocket Origin Verification
The WebSocket server must validate the Origin header during handshake and reject connections from untrusted origins. Combined with a short-lived JWT token passed as a query parameter on connection, this prevents cross-site WebSocket hijacking (CSWSH).
example.typescript
// WebSocket connection with auth token
function connectBoard(boardId: string, token: string) {
const ws = new WebSocket(
`wss://api.frontendx.dev/${boardId}?token=${token}`
);
return ws;
}
// Server-side: validate JWT + check board membership on every message
// Deny if user is not a member or token is expired
// Content-Security-Policy for boards with user-generated content
// Restrict img-src to controlled CDN, block inline scripts
const CSP = {
"default-src": "'self'",
"img-src": "'self' https://cdn.frontendx.dev data:",
"script-src": "'self'",
};
Warning
Do not store the session token in localStorage if the board may contain sensitive business data. Use an HTTP-only, SameSite cookie for authentication and only pass a short-lived JWT for WebSocket handshake. This limits the blast radius if an XSS is discovered in card content.
9. Testing Strategy
A kanban board has pure logic (state transitions, normalized data operations) and impure behavior (drag interactions, WebSocket events, offline lifecycle). We test them separately.
Unit Tests — Store Mutations
The Zustand store is pure logic — given a state and a mutation, it returns the next state. We test every mutation type (create, update, move, delete, rollback) with known inputs and assert on the resulting normalized state. These tests catch off-by-one errors in column reorder and ID mismatches.
Integration Tests — Drag Interactions
We mount the KanbanBoard with a mock fetch and mock WebSocket. We simulate dragend events and verify cards move between columns. We also simulate offline→online transitions and verify the mutation queue flushes in order.
E2E Tests — Full Board Workflow
Playwright drives a real browser. We create a board, add tasks, drag them between columns, verify the server persisted the move, and check that a second browser tab receives the WebSocket update.
example.typescript
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { KanbanBoard } from "./KanbanBoard";
describe("KanbanBoard", () => {
it("renders all four columns", () => {
render(<KanbanBoard boardId="board-1" />);
expect(screen.getByText("To Do")).toBeInTheDocument();
expect(screen.getByText("In Progress")).toBeInTheDocument();
expect(screen.getByText("In Review")).toBeInTheDocument();
expect(screen.getByText("Done")).toBeInTheDocument();
});
it("creates a task and shows it in the todo column", async () => {
render(<KanbanBoard boardId="board-1" />);
await userEvent.click(screen.getByLabelText("Add task"));
await userEvent.type(
screen.getByLabelText("Task title"),
"Fix login bug",
);
await userEvent.click(screen.getByRole("button", { name: "Save" }));
expect(screen.getByText("Fix login bug")).toBeInTheDocument();
});
it("updates task count when moving between columns", async () => {
render(<KanbanBoard boardId="board-1" />);
// Simulate drag end event directly
const board = screen.getByRole("region", { name: "Kanban board" });
fireEvent(board, new CustomEvent("dragend", {
detail: { active: { id: "task-1" }, over: { id: "in-progress" } },
}));
// Verify task moved
expect(screen.getByText("task-1")).toBeInTheDocument();
});
it("persists pending mutations when offline", () => {
const store = useKanbanStore.getState();
store.enqueuePending({
id: "mut-1", type: "task:moved",
payload: { taskId: "t1", toStatus: "done", order: 0 },
timestamp: Date.now(), retries: 0,
});
const persisted = JSON.parse(
localStorage.getItem("kanban-storage") ?? "{}",
);
expect(persisted.state.pendingMutations).toHaveLength(1);
});
});
Tip
The hardest test to write is the offline→online sync. Use Playwright's page.context().setOffline(true) to simulate disconnect, perform mutations, then bring the browser back online and verify the server received all queued mutations. This is the test that catches most bugs in production.
10. Accessibility
A drag-and-drop interface is inherently less accessible than a static page. We must provide keyboard alternatives, screen- reader announcements, and clear focus indicators so every interaction has a non-visual equivalent.
Keyboard Navigation: Each card is a focusable article with role="button" and tabIndex=0. Tab moves between cards; Enter or Space opens the detail modal. dnd-kit's KeyboardSensor provides arrow-key drag as a fallback.
ARIA Live Region: When a card moves between columns, a visually hidden aria-live="polite" region announces the move: "Fix login bug moved to In Progress." Screen-reader users are not left wondering where the card went.
Focus Management: When the detail modal opens, focus moves to the modal. When it closes, focus returns to the card that was activated. When a card is deleted, focus moves to the next card in the column or the column header if no cards remain.
Reduced Motion: All drag animations and column transitions respect prefers-reduced-motion: reduce. dnd-kit's animations are disabled when the media query is active.
Color Contrast: Priority labels use both color and text (e.g., "Critical" with a red dot) so color-blind users can distinguish them.
Test your kanban board with a keyboard only. If you can Tab through cards, open one, update its status, close it, and return to the same card, the accessibility is solid. TheKeyboardSensor from dnd-kit handles the drag equivalent — make sure it is wired.
Live Demo
Here is the kanban board running live. Drag cards between columns, create new tasks, add labels and due dates, and see the optimistic update in action. Open the browser console and toggle offline mode to watch the mutation queue in action.
Drag cards between columns. Create tasks with labels and due dates. Go offline and make changes — they sync on reconnect.