Back
๐Ÿ—๏ธ

Cheatsheet โ€” System Design

Protocols ยท Machine Coding ยท Performance ยท Storage ยท Security

๐Ÿ—๏ธ The Universal Machine Coding Checklist

Before Writing Any Code ๐Ÿง 

  • โœ“Clarify requirements โ€” functional & non-functional
  • โœ“Ask: what scale? (10 users vs 10M users)
  • โœ“Define data structures / state shape first
  • โœ“Identify: real-time needed? offline support?
  • โœ“Define component boundaries on paper
  • โœ“Identify edge cases (empty state, error state, loading state)
  • โœ“Ask about browser support / mobile requirements
  • โœ“Confirm: should you handle auth? pagination?
  • โœ“Agree on what NOT to implement (time-box scope)
  • โœ“Talk through your plan before coding

Every Component Needs These States ๐Ÿ”„

  • โš Loading state โ€” spinner / skeleton (not just the happy path!)
  • โš Error state โ€” show error message + retry action
  • โš Empty state โ€” no data yet (first time user experience)
  • โš Partial/edge data โ€” 0 items, 1 item, 10,000 items
// Pattern to always use
const [data, setData]     = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError]   = useState(null);

Accessibility Checklist โ™ฟ

  • โœ“Keyboard navigable (Tab, Enter, Escape, Arrow keys)
  • โœ“Proper ARIA roles / labels on interactive elements
  • โœ“Focus management on modal open/close
  • โœ“Alt text on all images
  • โœ“Color contrast โ€” do not rely on color alone
  • โœ“Announce dynamic changes with aria-live

Performance Checklist โšก

  • โœ“Debounce / throttle search inputs and scroll handlers
  • โœ“Virtualize long lists (react-virtual, react-window)
  • โœ“Lazy-load images (loading='lazy' or IntersectionObserver)
  • โœ“Memoize expensive computations (useMemo)
  • โœ“Stable callbacks to avoid child re-renders (useCallback + memo)
  • โœ“Code-split heavy components (React.lazy + Suspense)

๐ŸŽฏ Common Machine Coding Questions โ€” Key Points

Search Autocomplete

  • โœ“Debounce input (300ms) โ€” do not fire on every keystroke
  • โœ“Cancel previous request on new input (AbortController)
  • โœ“Cache results in a Map to avoid repeat fetches
  • โœ“Keyboard: ArrowUp/Down, Enter selects, Escape closes
  • โœ“ARIA: role='combobox', aria-expanded, role='listbox', role='option'
  • โœ“Highlight matched text in suggestions

Infinite Scroll / Pagination

  • โœ“IntersectionObserver on sentinel div at bottom โ€” no scroll listener
  • โœ“Show loading skeleton while fetching next page
  • โœ“Deduplicate items (server may return duplicates with cursor-based)
  • โœ“Handle network errors โ€” retry button, do not lose loaded data
  • โœ“Virtualize if list grows very large (1000+ items)
  • โœ“Choose: cursor-based (stable) vs offset-based (simpler but inconsistent)
const observer = new IntersectionObserver(([entry]) => {
  if (entry.isIntersecting && !loading) fetchNextPage();
}, { threshold: 0.1 });
observer.observe(sentinelRef.current);

File Upload

  • โœ“Show progress bar (XHR onprogress or fetch ReadableStream)
  • โœ“Validate: file type, size limit BEFORE upload
  • โœ“Allow drag-and-drop (ondragover + ondrop)
  • โœ“Multiple files โ€” queue them, upload concurrently or sequentially
  • โœ“Retry failed uploads, show per-file status
  • โœ“Chunked upload for large files (resumable)
// Progress with XHR
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (e) => {
  const pct = Math.round((e.loaded / e.total) * 100);
  setProgress(pct);
};

Real-time Chat

  • โœ“WebSocket for bidirectional messaging
  • โœ“Optimistic UI โ€” show message immediately, confirm async
  • โœ“Reconnect logic with exponential backoff
  • โœ“Scroll to bottom on new message (unless user has scrolled up)
  • โœ“Show typing indicators (debounced emit)
  • โœ“Presence (online/offline) via WebSocket heartbeat

Drag and Drop

  • โœ“HTML5 Drag API: draggable, ondragstart, ondragover, ondrop
  • โœ“preventDefault on ondragover to allow drop
  • โœ“Visual feedback โ€” highlight valid drop zones
  • โœ“dataTransfer.setData / getData to pass item id
  • โœ“Touch support needs separate pointer event handling
  • โœ“Keyboard alternative for accessibility
el.ondragstart = (e) => e.dataTransfer.setData("id", item.id);
drop.ondragover = (e) => e.preventDefault(); // required!
drop.ondrop = (e) => {
  const id = e.dataTransfer.getData("id");
  reorder(id);
};

Modal / Toast / Tooltip

  • โœ“Modal: Portal to body, focus trap, lock body scroll, close on Escape
  • โœ“Restore focus to trigger element on close
  • โœ“Toast: auto-dismiss with timer, pause on hover, accessible aria-live='polite'
  • โœ“Tooltip: show on hover + focus (keyboard users too!), useRef for positioning
  • โœ“Overlay click closes modal โ€” but not click inside modal

Form with Validation

  • โœ“Validate on blur (not on every keystroke) to avoid annoying UX
  • โœ“Re-validate on submit
  • โœ“Disabled submit until valid โ€” or allow submit and show all errors
  • โœ“Show inline errors, not just a toast
  • โœ“Handle async validation (email availability check โ€” debounce!)
  • โœ“Consider React Hook Form or Zod for complex forms

Virtualized List (10k+ items)

  • โœ“Only render visible items + overscan buffer
  • โœ“Calculate item positions from known / estimated heights
  • โœ“For variable height: measure with ResizeObserver, store heights
  • โœ“Scroll restoration when navigating away and back
// Core idea
const ITEM_HEIGHT = 40;
const visibleStart = Math.floor(scrollTop / ITEM_HEIGHT);
const visibleEnd   = Math.ceil((scrollTop + containerH) / ITEM_HEIGHT);
// Render only items[visibleStart..visibleEnd]
// Spacer div for total height