Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
65

Frontend System Design · Lesson 65 of 86 · 4 min

Push Notifications for Web Apps

This comes up when designing any system that needs to re-engage users, like social media, e-commerce, or chat apps. You need to know the end-to-end flow.

After this, you'll be able to explain the full architecture of a web push notification system, from the user granting permission on the client to your server triggering a push. You will know the roles of the service worker, your backend, and the third-party push services that connect them.

The End-to-End Architecture

A push notification system has three main actors: your web app (the client), your application server (the backend), and a third-party Push Service.

The Push Service is the critical intermediary. It's a service provided by the browser vendor (e.g., Google's FCM, Apple's APNS) that maintains a persistent connection to the user's device. This is a hard problem you don't want to solve; it involves managing millions of connections, optimizing for battery life, and queuing messages for offline devices. Your job is to connect the pieces.

The entire flow looks like this:

Your server authenticates itself to the Push Service using VAPID (Voluntary Application Server Identification) keys. This is a public/private key pair. The public key is given to the client when it subscribes, and the private key is used by your server to sign the push request. This proves the request came from you.

The Client-Side: Subscribing the User

The frontend's first job is to get the user's permission and a PushSubscription object. This object contains a unique endpoint URL provided by the Push Service—it's the address your server will send messages to.

The flow is always:

  1. Register a service worker.
  2. Request notification permission from the user.
  3. If granted, use the pushManager.subscribe() method to get a PushSubscription.
  4. Send this subscription object to your backend to be stored.

The trap: Asking for permission on page load. Users will reflexively click "Block" on a prompt from a site they just landed on. Instead, ask for permission in response to a specific user action that implies interest, like clicking a "Notify me of new messages" button. Make the value proposition clear before showing the native browser prompt.

This is the code to get a subscription and send it to your server.

// In your main application code
async function subscribeUser() {
  if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
    console.warn('Push notifications are not supported.');
    return;
  }

  const registration = await navigator.serviceWorker.register('/sw.js');
  const permission = await Notification.requestPermission();

  if (permission !== 'granted') {
    console.warn('Permission was not granted.');
    return;
  }

  // This VAPID key is generated on your server and is safe to expose.
  const applicationServerKey = 'YOUR_VAPID_PUBLIC_KEY';
  const options = {
    userVisibleOnly: true,
    applicationServerKey,
  };

  const subscription = await registration.pushManager.subscribe(options);

  // Send the subscription object to your backend.
  await fetch('/api/save-subscription', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(subscription),
  });
}

The userVisibleOnly: true option is mandatory. It's a promise to the browser that every push message will result in a visible notification. This prevents developers from silently tracking users in the background.

The Service Worker: Receiving and Displaying

The service worker does the actual work when a push message arrives. It runs in the background, separate from your main application tab. The browser wakes it up when a push message is delivered by the Push Service.

You need to listen for two key events: push and notificationclick.

The push event fires when a message arrives. Your handler parses the payload and calls self.registration.showNotification() to display it.

The notificationclick event fires when the user taps the notification. Your handler should open a relevant window or focus an existing one. A notification that does nothing when clicked is a dead end and a poor user experience.

Key detail: Any async work inside these event handlers must be wrapped in event.waitUntil(). This tells the browser to keep the service worker alive until your promise resolves. Without it, the service worker might be terminated mid-operation.

// In sw.js
self.addEventListener('push', (event) => {
  const payload = event.data ? event.data.json() : {};
  const title = payload.title || 'New Notification';
  const options = {
    body: payload.body || 'Something new happened!',
    icon: '/images/icon-192x192.png',
    data: {
      url: payload.url || '/',
    },
  };

  event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', (event) => {
  // Close the notification
  event.notification.close();

  const targetUrl = event.notification.data.url;

  // Focus an existing window or open a new one
  event.waitUntil(
    clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
      for (const client of clientList) {
        if (client.url === targetUrl && 'focus' in client) {
          return client.focus();
        }
      }
      if (clients.openWindow) {
        return clients.openWindow(targetUrl);
      }
    })
  );
});

A push can also be "silent"—triggering the push event without displaying a notification. You can use this to sync data in the background, which is a powerful technique for offline-first apps, as discussed in the lesson on Offline Support and Background Sync.

Handling Payloads and Server Logic

Your backend stores the PushSubscription objects, usually mapped to a user ID. When an event occurs (e.g., a new message arrives), the server retrieves the relevant subscription(s) and sends a request to the endpoint URL.

Interview angle: A common question is how to handle expired subscriptions. If a user revokes permission or clears their browser data, the subscription becomes invalid. When your server tries to send a message to that endpoint, the Push Service will respond with a 410 GONE status code. Your backend must be designed to catch this response and delete the stale subscription from your database. This demonstrates you've thought about system maintenance and efficiency.

You also have to decide what goes into the push payload.

  • Small payloads (a few KB): Send all necessary data directly in the push message (e.g., a chat message's text). The service worker can display it immediately. This is fast and simple.
  • Large or sensitive data: Send a minimal payload, like an ID or a "new data available" flag. The service worker's push handler then fetches the full data from your API. This keeps the push message light but adds a network request, introducing latency.

Try it

Use a library like web-push for Node.js to generate a VAPID key pair. Then, using the client-side code from this lesson, create a simple HTML page with a button. When clicked, it should request permission and log the resulting PushSubscription object to the console. This should take about 20 minutes.

Next: We'll compare the tools that bundle your code for production in Webpack vs Vite vs Parcel.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Offline Support and Background Sync

Next

Webpack vs Vite vs Parcel