<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shridhar Mani Tripathi on Medium]]></title>
        <description><![CDATA[Stories by Shridhar Mani Tripathi on Medium]]></description>
        <link>https://medium.com/@shridharmanitripathi?source=rss-1c90afdf26df------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Shridhar Mani Tripathi on Medium</title>
            <link>https://medium.com/@shridharmanitripathi?source=rss-1c90afdf26df------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 22:39:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shridharmanitripathi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Refactoring React at Scale: Reducing Technical Debt Without Breaking Existing Workflows]]></title>
            <link>https://medium.com/@shridharmanitripathi/refactoring-react-at-scale-reducing-technical-debt-without-breaking-existing-workflows-de4d786ab136?source=rss-1c90afdf26df------2</link>
            <guid isPermaLink="false">https://medium.com/p/de4d786ab136</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[technical-debt]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Shridhar Mani Tripathi]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 11:56:58 GMT</pubDate>
            <atom:updated>2026-11-18T11:56:58.634Z</atom:updated>
            <content:encoded><![CDATA[<p>Refactoring a component in isolation is relatively easy.</p><p>Refactoring a component that is shared across multiple workflows, connected to global state, dependent on backend APIs, and already used in production is a very different problem.</p><figure><img alt="Illustration comparing a complex React application before and after refactoring. The left side shows tangled conditional logic, technical debt, shared-component issues, state synchronization problems, duplicate API calls, and hidden dependencies." src="https://cdn-images-1.medium.com/max/1024/1*pqDL5r4YTowHSyEBy4ns4g.png" /></figure><p>In a mature React application, the question is rarely:</p><blockquote>How can I make this code cleaner?</blockquote><p>A more useful question is:</p><blockquote><strong><em>How can I improve this code without breaking the behaviour that other parts of the application already depend on?</em></strong></blockquote><p>Over time, I have worked on frontend modules that started with relatively simple responsibilities but gradually accumulated shared components, workflow-specific conditions, state synchronization, effects, API dependencies, and reusable business logic.</p><p>Eventually, a change that appears local can affect an entirely different workflow.</p><p>At that point, refactoring stops being purely about clean code.</p><p>It becomes an exercise in <strong>managing change safely</strong>.</p><h3>Understand Why the Complexity Exists</h3><p>When opening a large component, it can be tempting to immediately start extracting components, removing conditions, and simplifying state.</p><p>But mature code often became complicated for legitimate reasons.</p><p>A component may have started like this:</p><pre>&lt;Details data={data} /&gt;</pre><p>Then one workflow required editing:</p><pre>&lt;Details data={data} editable /&gt;</pre><p>Another required additional actions:</p><pre>&lt;Details<br>  data={data}<br>  editable<br>  showActions<br>  onSave={handleSave}<br>/&gt;</pre><p>Eventually:</p><pre>Simple Component<br>      ↓<br>More Requirements<br>      ↓<br>Shared Across Workflows<br>      ↓<br>Special Cases<br>      ↓<br>More State and Effects</pre><p>Before changing the implementation, I try to understand:</p><ul><li>Which behaviour is shared?</li><li>Which behaviour is workflow-specific?</li><li>Which existing modules depend on it?</li><li>What assumptions are hidden inside the current implementation?</li></ul><p>The first objective is not to make the code cleaner.</p><p>It is to <strong>understand the behaviour that must survive the refactor</strong>.</p><h3>Reuse the Invariants, Not Every Similarity</h3><p>One of the easiest traps in React refactoring is assuming that less duplication automatically means better architecture.</p><p>Suppose three workflows use similar screens:</p><pre>                 Shared Component<br>                      │<br>          ┌───────────┼───────────┐<br>          │           │           │<br>     Workflow A  Workflow B  Workflow C</pre><p>A common response is to make one highly configurable component:</p><pre>&lt;CommonComponent<br>  isWorkflowA={...}<br>  isWorkflowB={...}<br>  enableSpecialValidation={...}<br>  showAdditionalActions={...}<br>  useAlternateSave={...}<br>/&gt;</pre><p>Duplication decreases, but complexity does not necessarily decrease.</p><p>It may simply move into one shared component.</p><p>Instead, I prefer identifying the <strong>invariants</strong>:</p><pre>               Shared Foundation<br>                      │<br>          ┌───────────┼───────────┐<br>          │           │           │<br>     Workflow A  Workflow B  Workflow C<br>       variation     variation     variation</pre><p>The shared layer owns stable behaviour.</p><p>Each workflow owns the behaviour that genuinely makes it different.</p><p>This leads to a useful principle:</p><blockquote><strong><em>Reuse should centralize what is truly common, not hide legitimate variation.</em></strong></blockquote><h3>State Synchronization Is Often a State-Ownership Problem</h3><p>Some of the hardest React bugs I have encountered came from unclear state ownership rather than complicated algorithms.</p><p>Consider:</p><pre>Server<br>  ↓<br>Parent State<br>  ↓<br>Child Local State<br>  ↓<br>User Modification<br>  ↓<br>Parent Update<br>  ↓<br>Child Synchronisation</pre><p>Now add asynchronous requests:</p><pre>Request A starts<br>      ↓<br>User changes state<br>      ↓<br>Request B starts<br>      ↓<br>Request B completes<br>      ↓<br>Request A completes<br>      ↓<br>Older state overwrites newer state</pre><p>The visible symptoms may look unrelated:</p><ul><li>a selected value suddenly disappears;</li><li>saved data replaces a newer edit;</li><li>a component works only after refresh;</li><li>an API is unexpectedly called again.</li></ul><p>The immediate temptation is often to add another useEffect.</p><p>Before doing that, I now ask:</p><ol><li>Who actually owns this state?</li><li>Which value is the source of truth?</li><li>Does the child need its own copy?</li><li>Can this value be derived instead of stored?</li><li>Can an asynchronous response overwrite newer user intent?</li></ol><p>Reducing the number of independently mutable representations of the same information often removes entire categories of synchronization bugs.</p><h3>Treat useEffect Chains and Duplicate API Calls as Architectural Clues</h3><p>Consider several individually reasonable effects:</p><pre>useEffect(() =&gt; {<br>  fetchData(selectedItem);<br>}, [selectedItem]);<br><br>useEffect(() =&gt; {<br>  if (response) {<br>    setSelectedItem(response.item);<br>  }<br>}, [response]);</pre><p>It is easy to accidentally create:</p><pre>State changes<br>     ↓<br>Effect runs<br>     ↓<br>API request<br>     ↓<br>Response updates state<br>     ↓<br>Effect runs again</pre><p>Eventually someone reports:</p><blockquote><em>“The API is being called twice.”</em></blockquote><p>The duplicate request is often only the symptom.</p><p>When debugging these problems, I trace the complete state transition:</p><pre>What changed?<br>     ↓<br>What depends on it?<br>     ↓<br>What does that dependency modify?<br>     ↓<br>Does that modification affect the original value?</pre><p>The same principle applies when two components fetch the same data or when parent and child components both believe they own initialization.</p><p>Sometimes the solution is a guard or a ref.</p><p>But sometimes a duplicate API call is telling us something more important:</p><blockquote><strong><em>The system does not have a clear owner for that responsibility.</em></strong></blockquote><h3>Refactor Responsibilities, Not Line Counts</h3><p>Large components often contain several concerns:</p><pre>Component<br>   │<br>   ├── API communication<br>   ├── State coordination<br>   ├── Validation<br>   ├── Domain transformations<br>   ├── Workflow-specific behaviour<br>   └── Rendering</pre><p>The goal should not simply be:</p><blockquote>This file has 800 lines. Let’s split it.</blockquote><p>A better question is:</p><blockquote><strong><em>Which responsibilities change for different reasons?</em></strong></blockquote><p>That creates much more useful boundaries.</p><p>An API transformation does not necessarily belong inside a rendering component.</p><p>Workflow-specific behaviour does not necessarily belong in a shared component.</p><p>Derived state may not need to be state at all.</p><p>Refactoring around responsibility makes future changes easier to localize.</p><h3>Prefer Incremental Refactoring to Heroic Rewrites</h3><p>A rewrite is attractive because the new implementation starts without years of accumulated complexity.</p><p>It also starts without years of accumulated knowledge.</p><p>The existing code may contain behaviour that is not obvious from the current requirements:</p><pre>Old System<br>   ↓<br>Years of Requirements<br>   ↓<br>Special Cases<br>   ↓<br>Production Behaviour<br>   ↓<br>Hidden Assumptions</pre><p>Replacing everything at once means rediscovering all of those assumptions.</p><p>For mature applications, I prefer:</p><pre>Understand<br>    ↓<br>Identify a boundary<br>    ↓<br>Isolate behaviour<br>    ↓<br>Change one responsibility<br>    ↓<br>Verify existing workflows<br>    ↓<br>Continue</pre><p>This may appear slower than rewriting the module.</p><p>But the real cost of a refactor is not measured only in development time.</p><p>It also includes <strong>the regressions introduced by changing stable behaviour</strong>.</p><h3>Think in Terms of Regression Surface</h3><p>This has become one of the most useful ways for me to think about frontend architecture.</p><p>Imagine a new workflow requires changing:</p><pre>Shared Component<br>Global State<br>Navigation<br>API Utility<br>Workflow A<br>Workflow B<br>New Workflow C</pre><p>The <strong>regression surface</strong> is large.</p><p>If clearer boundaries allow the same feature to require:</p><pre>New Workflow C<br>Configuration<br>One shared extension point</pre><p>the regression surface becomes smaller.</p><p>That does not guarantee correctness.</p><p>It does, however, reduce the amount of stable behaviour that must change whenever a new requirement arrives.</p><p>For me, that is one of the most practical indicators of improving architecture:</p><blockquote><strong><em>Does the next feature require changing fewer unrelated parts of the system?</em></strong></blockquote><h3>What I Have Learned</h3><p>Working with mature React applications has changed how I think about refactoring.</p><p>I used to associate it mainly with:</p><pre>Smaller components<br>Less duplication<br>Better naming<br>Reusable functions</pre><p>Those things still matter.</p><p>But I now think about refactoring more broadly:</p><blockquote><strong><em>Refactoring is not just improving code structure. It is improving structure while controlling the risk created by changing it.</em></strong></blockquote><p>That changes the questions I ask.</p><p>Instead of:</p><blockquote>Can I make this component reusable?</blockquote><p>I ask:</p><blockquote><strong><em>Which parts are genuinely invariant?</em></strong></blockquote><p>Instead of:</p><blockquote>How do I stop this effect from running twice?</blockquote><p>I ask:</p><blockquote><strong><em>Which state transition caused the second execution?</em></strong></blockquote><p>Instead of:</p><blockquote>Why is this code so complicated?</blockquote><p>I ask:</p><blockquote><strong><em>Which requirements caused the complexity to exist?</em></strong></blockquote><p>And instead of:</p><blockquote>Would rewriting this be cleaner?</blockquote><p>I ask:</p><blockquote><strong><em>What existing behaviour would I have to rediscover during the rewrite?</em></strong></blockquote><h3>Final Thoughts</h3><p>Large React applications rarely become difficult because of one terrible architectural decision.</p><p>Complexity accumulates gradually.</p><p>A requirement is added. Another workflow reuses the component. A condition appears. State is duplicated. An effect is introduced. Another module starts depending on the behaviour.</p><p>Each decision may be reasonable on its own.</p><p>The objective of refactoring should therefore not be to make a mature codebase look as though it were designed yesterday.</p><p>Its history is part of the system.</p><p>The objective is simpler:</p><blockquote><strong><em>Make the next change safer than the previous one.</em></strong></blockquote><p>If a refactor establishes clearer state ownership, isolates workflow variation, reduces unnecessary coupling, and allows future requirements to touch fewer unrelated parts of the application, then the architecture has improved.</p><p>Not because the code becomes prettier.</p><p>Because <strong>the system becomes safer to change.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de4d786ab136" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing an Event-Driven Frontend Platform: From WebSockets to Registry-Based Workflows]]></title>
            <link>https://medium.com/@shridharmanitripathi/designing-an-event-driven-frontend-platform-from-websockets-to-registry-based-workflows-77a80078cc2c?source=rss-1c90afdf26df------2</link>
            <guid isPermaLink="false">https://medium.com/p/77a80078cc2c</guid>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <dc:creator><![CDATA[Shridhar Mani Tripathi]]></dc:creator>
            <pubDate>Fri, 11 Sep 2026 12:09:32 GMT</pubDate>
            <atom:updated>2026-09-11T12:09:32.847Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0tpo4nl40PxA9e0773y0kA.png" /></figure><p>Real-time functionality in a frontend application often begins with a simple requirement:</p><blockquote><em>Receive a message from the server and show it to the user.</em></blockquote><p>At first, the implementation appears straightforward. Open a WebSocket connection, listen for messages, update the interface, and move on to the next feature.</p><p>That works until the application grows.</p><p>As modules become more interconnected, a real-time notification can begin triggering state updates, navigation, workflow context, acknowledgements, data refreshes, analytics, and actions in modules that did not previously communicate with one another.</p><p>At that point, the challenge is no longer just receiving messages.</p><p>The challenge becomes:</p><blockquote><em>How can independent frontend modules respond to real-time events without becoming directly dependent on one another?</em></blockquote><p>This article describes one approach to that problem using:</p><ul><li>a central WebSocket manager;</li><li>a lightweight Event Bus;</li><li>explicit event contracts;</li><li>registry-based behaviour resolution;</li><li>isolated React listeners;</li><li>clear separation between transport, distribution, configuration, and business logic.</li></ul><p>The objective is not to present this as the only valid architecture. It is to demonstrate how a feature-specific WebSocket implementation can evolve into a reusable communication capability for a growing frontend application.</p><h3>The Problem Most Large Frontend Applications Eventually Face</h3><p>Communication in a small React application is usually straightforward.</p><p>A component needs information from another component.</p><p>A callback is passed.</p><p>A Redux action is dispatched.</p><p>A hook is shared.</p><p>A context value is updated.</p><p>Everything works.</p><p>As the application grows, however, workflows start crossing module boundaries.</p><p>For example:</p><ul><li>a background process completes and several screens need to refresh;</li><li>an item is assigned to a user and a notification must appear immediately;</li><li>selecting a notification must open another module with the correct context;</li><li>multiple features need to react to the same server-side event;</li><li>a message must update global state, display a toast, play a sound, and trigger navigation;</li><li>a disconnected client must reconnect without each module managing the connection.</li></ul><p>The application can gradually evolve into something like this:</p><pre>Module A -&gt; Notification Module<br>Module A -&gt; Dashboard<br>Module A -&gt; Module B<br>Module B -&gt; Module C<br>Module C -&gt; Global State</pre><p>This remains manageable while the number of integrations is small.</p><p>Eventually, several problems emerge:</p><ul><li>modules acquire direct knowledge of one another;</li><li>transport handling is duplicated;</li><li>business logic becomes mixed with connection logic;</li><li>event-specific conditions spread across the codebase;</li><li>adding a workflow requires modifying multiple existing modules;</li><li>testing becomes difficult because components depend on unrelated features;</li><li>small changes carry greater regression risk.</li></ul><p>The central problem is not necessarily React, Redux, or WebSockets.</p><p>The problem is that communication has been implemented as a collection of feature-specific integrations rather than as a platform capability.</p><h3>Identifying the Actual Requirement</h3><p>Initially, the requirement may look like a real-time notification feature.</p><p>A server sends a message:</p><pre>{<br>  &quot;type&quot;: &quot;ORDER_APPROVED&quot;,<br>  &quot;message&quot;: &quot;An order has been approved&quot;<br>}</pre><p>The frontend displays it:</p><pre>socket.onmessage = (event) =&gt; {<br>  const message = JSON.parse(event.data);<br>  showNotification(message.message);<br>};</pre><p>This is acceptable when displaying a notification is the only required behaviour.</p><p>In a larger application, the same event may need to:</p><ol><li>appear in a global notification list;</li><li>update an unread counter;</li><li>display a toast;</li><li>inform another feature;</li><li>preserve workflow context;</li><li>open a target module when selected;</li><li>acknowledge that the message was seen;</li><li>refresh related data.</li></ol><p>Placing all of this inside socket.onmessage would make the WebSocket layer responsible for business behaviour.</p><p>That is where the real requirement becomes clearer:</p><pre>Producers emit events<br>        ↓<br>Consumers react independently<br>        ↓<br>Neither side knows about the other</pre><p>To achieve this, the architecture must separate:</p><ul><li>message transport;</li><li>event distribution;</li><li>event definitions;</li><li>workflow configuration;</li><li>module-specific behaviour.</li></ul><h3>Architectural Overview</h3><p>The resulting design can be represented as:</p><pre>Server<br>  ↓<br>WebSocket Manager<br>  ↓<br>Event Bus<br>  ↓<br>Event Listeners<br>  ↓<br>Registry Resolution<br>  ↓<br>State, Navigation, UI and Business Modules</pre><p>Each layer has a clearly defined responsibility:</p><pre>WebSocket Manager<br>    Transport and connection reliability<br><br>Event Bus<br>    In-process event distribution<br><br>Event Contracts<br>    Shared communication vocabulary<br><br>Registry<br>    Behaviour and workflow configuration<br><br>React Listeners<br>    Lifecycle-aware subscriptions<br><br>Business Modules<br>    Feature-specific state and behaviour</pre><p>The key rule is that no layer should unnecessarily absorb the responsibilities of another.</p><h3>Layer 1: Centralised WebSocket Infrastructure</h3><p>The first architectural decision was to prevent individual features from creating and managing their own WebSocket connections.</p><p>Without a central manager, several modules may independently do this:</p><pre>const socket = new WebSocket(url);<br><br>socket.onmessage = (event) =&gt; {<br>  // Feature-specific handling<br>};</pre><p>That leads to duplicated concerns:</p><ul><li>authentication;</li><li>connection tracking;</li><li>reconnection;</li><li>heartbeat management;</li><li>cleanup;</li><li>message parsing;</li><li>error handling;</li><li>connection monitoring.</li></ul><p>Instead, a central WebSocket manager owns the transport lifecycle.</p><p>A simplified implementation might begin like this:</p><pre>class WebSocketManager {<br>  constructor() {<br>    this.sockets = new Map();<br>    this.connecting = new Set();<br>    this.reconnectAttempts = new Map();<br>  }<br><br>  connect(url) {<br>    if (this.sockets.has(url) || this.connecting.has(url)) {<br>      return;<br>    }<br><br>    this.connecting.add(url);<br><br>    const socket = new WebSocket(url);<br><br>    socket.onopen = () =&gt; {<br>      this.connecting.delete(url);<br>      this.reconnectAttempts.delete(url);<br>      this.sockets.set(url, socket);<br>    };<br><br>    socket.onerror = (error) =&gt; {<br>      console.error(&quot;[WebSocket] Connection error&quot;, error);<br>    };<br><br>    socket.onclose = (event) =&gt; {<br>      this.cleanup(url);<br><br>      if (event.code !== 1000) {<br>        this.scheduleReconnect(url);<br>      }<br>    };<br>  }<br><br>  cleanup(url) {<br>    this.sockets.delete(url);<br>    this.connecting.delete(url);<br>  }<br>}<br><br>export const webSocketManager = new WebSocketManager();</pre><p>The sockets map allows the manager to support more than one endpoint while ensuring that only one connection exists for each endpoint.</p><p>The connecting set prevents duplicate connection attempts when several callers try to initialise the same socket simultaneously.</p><h3>Authentication</h3><p>A production application will normally need to authenticate the WebSocket connection.</p><p>The exact method depends on the constraints and security model of the backend. Possible approaches include:</p><ul><li>an authenticated secure cookie;</li><li>a short-lived WebSocket connection token;</li><li>an authorised handshake endpoint;</li><li>an agreed WebSocket subprotocol.</li></ul><p>Credentials should not be placed in a URL query string unless the security implications have been explicitly assessed, because URLs can appear in logs and monitoring systems.</p><p>The transport layer should obtain authentication information through a dedicated authentication service rather than allowing feature modules to manage tokens directly.</p><p>Conceptually:</p><pre>async connect(url) {<br>  const authenticated = await authService.isAuthenticated();<br><br>  if (!authenticated) {<br>    return;<br>  }<br><br>  const connectionToken =<br>    await authService.getShortLivedWebSocketToken();<br><br>  const socket = new WebSocket(<br>    url,<br>    [`app-auth.${connectionToken}`]<br>  );<br><br>  // Configure socket lifecycle...<br>}</pre><p>The example is intentionally conceptual. The actual authentication protocol must be agreed with the backend and security teams.</p><h3>Connection Reliability</h3><p>Real-time applications need to detect stale connections.</p><p>A browser may appear online even though the underlying connection is no longer usable. If no health mechanism exists, the interface may silently stop receiving updates.</p><p>A heartbeat introduces an application-level health check:</p><pre>Client -&gt; PING<br>Server -&gt; PONG</pre><p>A simplified implementation could look like this:</p><pre>class WebSocketManager {<br>  constructor() {<br>    this.sockets = new Map();<br>    this.heartbeatIntervals = new Map();<br>    this.heartbeatTimeouts = new Map();<br>  }<br><br>  startHeartbeat(url) {<br>    this.stopHeartbeat(url);<br><br>    const intervalId = setInterval(() =&gt; {<br>      const socket = this.sockets.get(url);<br><br>      if (!socket || socket.readyState !== WebSocket.OPEN) {<br>        return;<br>      }<br><br>      socket.send(<br>        JSON.stringify({<br>          type: &quot;PING&quot;,<br>          timestamp: Date.now()<br>        })<br>      );<br><br>      const timeoutId = setTimeout(() =&gt; {<br>        console.warn(&quot;[WebSocket] Heartbeat timed out&quot;, url);<br>        socket.close();<br>      }, 30_000);<br><br>      this.heartbeatTimeouts.set(url, timeoutId);<br>    }, 15_000);<br><br>    this.heartbeatIntervals.set(url, intervalId);<br>  }<br><br>  acknowledgeHeartbeat(url) {<br>    const timeoutId = this.heartbeatTimeouts.get(url);<br><br>    if (timeoutId) {<br>      clearTimeout(timeoutId);<br>      this.heartbeatTimeouts.delete(url);<br>    }<br>  }<br><br>  stopHeartbeat(url) {<br>    clearInterval(this.heartbeatIntervals.get(url));<br>    clearTimeout(this.heartbeatTimeouts.get(url));<br><br>    this.heartbeatIntervals.delete(url);<br>    this.heartbeatTimeouts.delete(url);<br>  }<br>}</pre><p>When a valid message or PONG response arrives, the pending timeout is cleared:</p><pre>socket.onmessage = (event) =&gt; {<br>  this.acknowledgeHeartbeat(url);<br><br>  if (event.data === &quot;PONG&quot;) {<br>    return;<br>  }<br><br>  // Route the message<br>};</pre><p>A heartbeat does not guarantee delivery, but it allows the client to detect a silent failure and initiate recovery.</p><h3>Reconnection Strategy</h3><p>Unexpected disconnections require controlled reconnection.</p><p>A naïve implementation may reconnect immediately and indefinitely:</p><pre>socket.onclose = () =&gt; {<br>  connect(url);<br>};</pre><p>This can create a reconnect storm if the backend is unavailable.</p><p>A safer approach limits attempts and increases the delay between them:</p><pre>scheduleReconnect(url) {<br>  const previousAttempts =<br>    this.reconnectAttempts.get(url) ?? 0;<br><br>  const nextAttempt = previousAttempts + 1;<br><br>  if (nextAttempt &gt; 5) {<br>    eventBus.emit(&quot;CONNECTION_UNAVAILABLE&quot;, {<br>      url,<br>      attempts: previousAttempts<br>    });<br><br>    return;<br>  }<br><br>  this.reconnectAttempts.set(url, nextAttempt);<br><br>  const baseDelay = 3000;<br>  const maximumDelay = 30000;<br><br>  const delay = Math.min(<br>    baseDelay * 2 * (nextAttempt - 1),<br>    maximumDelay<br>  );<br><br>  setTimeout(() =&gt; {<br>    this.connect(url);<br>  }, delay);<br>}</pre><p>A production implementation can also add random jitter, reducing the chance that many clients reconnect at exactly the same time.</p><p>The important point is that reconnection remains a transport responsibility.</p><p>Business modules should not implement their own recovery loops.</p><h3>Sending Messages Safely</h3><p>Some workflows require bidirectional communication, such as acknowledging a notification.</p><p>The manager can provide one central send operation:</p><pre>send(url, payload) {<br>  const socket = this.sockets.get(url);<br><br>  if (!socket) {<br>    return false;<br>  }<br><br>  if (socket.readyState === WebSocket.OPEN) {<br>    socket.send(JSON.stringify(payload));<br>    return true;<br>  }<br><br>  if (socket.readyState === WebSocket.CONNECTING) {<br>    socket.addEventListener(<br>      &quot;open&quot;,<br>      () =&gt; socket.send(JSON.stringify(payload)),<br>      { once: true }<br>    );<br><br>    return true;<br>  }<br><br>  return false;<br>}</pre><p>This keeps serialisation rules and connection-state checks out of business modules.</p><p>Whether messages should be queued while disconnected is a separate design decision. A queue may help some systems, but it can also create stale or duplicate actions. It should not be added without defining expiry, ordering, retry, and idempotency rules.</p><h3>Why We Didn’t Stop at WebSockets</h3><p>At first, WebSockets appeared to solve the problem.</p><p>The server could push messages to the browser.</p><p>The frontend could react immediately.</p><p>A basic architecture looked like this:</p><pre>Server<br>  ↓<br>WebSocket<br>  ↓<br>Feature</pre><p>The problem emerged as additional event types were introduced.</p><p>A typical message handler began accumulating business logic:</p><pre>socket.onmessage = (event) =&gt; {<br>  const message = JSON.parse(event.data);<br><br>  switch (message.type) {<br>    case &quot;ORDER_CREATED&quot;:<br>      showOrderNotification(message);<br>      refreshOrderList();<br>      break;<br><br>    case &quot;DOCUMENT_APPROVED&quot;:<br>      updateDocumentState(message);<br>      refreshDashboard();<br>      break;<br><br>    case &quot;USER_ASSIGNED&quot;:<br>      updateAssignmentCount(message);<br>      openAssignmentToast(message);<br>      break;<br><br>    default:<br>      console.warn(&quot;Unknown event&quot;, message.type);<br>  }<br>};</pre><p>This works, but the WebSocket handler is now responsible for:</p><ul><li>parsing transport data;</li><li>deciding what an event means;</li><li>modifying application state;</li><li>refreshing features;</li><li>triggering user-interface behaviour;</li><li>coordinating unrelated modules.</li></ul><p>Every new workflow requires another modification to the transport layer.</p><p>That leads to a critical distinction:</p><blockquote><em>WebSockets solve transport. They do not, by themselves, provide a frontend communication architecture.</em></blockquote><p>A WebSocket should ideally do only this:</p><pre>Receive message<br>      ↓<br>Validate envelope<br>      ↓<br>Publish event</pre><p>It should not decide how the rest of the application responds.</p><p>The revised flow therefore became:</p><pre>Server<br>  ↓<br>WebSocket Manager<br>  ↓<br>Event Bus<br>  ↓<br>Independent Subscribers</pre><p>The WebSocket layer could now remain stable while application behaviour evolved independently.</p><p>A simplified bridge looks like this:</p><pre>socket.onmessage = (event) =&gt; {<br>  this.acknowledgeHeartbeat(url);<br><br>  if (event.data === &quot;PONG&quot;) {<br>    return;<br>  }<br><br>  let message;<br><br>  try {<br>    message = JSON.parse(event.data);<br>  } catch (error) {<br>    console.warn(&quot;[WebSocket] Invalid JSON message&quot;, error);<br>    return;<br>  }<br><br>  if (!message?.type) {<br>    console.warn(&quot;[WebSocket] Missing event type&quot;, message);<br>    return;<br>  }<br><br>  eventBus.emit(message.type, message);<br>};</pre><p>Notice what is deliberately absent:</p><ul><li>no Redux dispatch;</li><li>no navigation;</li><li>no toast;</li><li>no module import;</li><li>no feature-specific switch statement.</li></ul><p>The WebSocket manager knows that a message has a type and payload. It does not know what that message means to the business.</p><p>That responsibility belongs to subscribers and workflow configuration.</p><h3>Layer 2: Building the Event Bus</h3><p>The Event Bus provides in-process Pub/Sub communication.</p><p>Its public API can remain intentionally small:</p><pre>eventBus.on(eventType, handler);<br>eventBus.off(eventType, handler);<br>eventBus.emit(eventType, payload);</pre><p>A practical implementation can use a Map of event names and a Set of handlers:</p><pre>class EventBus {<br>  constructor() {<br>    this.listeners = new Map();<br>  }<br><br>  on(eventType, handler) {<br>    if (!eventType || typeof handler !== &quot;function&quot;) {<br>      throw new Error(<br>        &quot;A valid event type and handler are required&quot;<br>      );<br>    }<br><br>    if (!this.listeners.has(eventType)) {<br>      this.listeners.set(eventType, new Set());<br>    }<br><br>    this.listeners.get(eventType).add(handler);<br><br>    return () =&gt; this.off(eventType, handler);<br>  }<br><br>  off(eventType, handler) {<br>    const handlers = this.listeners.get(eventType);<br><br>    if (!handlers) {<br>      return;<br>    }<br><br>    handlers.delete(handler);<br><br>    if (handlers.size === 0) {<br>      this.listeners.delete(eventType);<br>    }<br>  }<br><br>  emit(eventType, payload) {<br>    const handlers = this.listeners.get(eventType);<br><br>    if (!handlers) {<br>      return;<br>    }<br><br>    [...handlers].forEach((handler) =&gt; {<br>      try {<br>        handler(payload);<br>      } catch (error) {<br>        console.error(<br>          `[EventBus] Handler failed for ${eventType}`,<br>          error<br>        );<br>      }<br>    });<br>  }<br><br>  getRegisteredEvents() {<br>    return [...this.listeners.keys()];<br>  }<br>}<br><br>export const eventBus = new EventBus();</pre><p>Using a Set provides two useful properties:</p><ol><li>The same handler is not registered repeatedly for the same event.</li><li>Removing a handler is straightforward.</li></ol><p>Returning an unsubscribe function from on also makes lifecycle management more convenient:</p><pre>const unsubscribe = eventBus.on(<br>  &quot;ORDER_CREATED&quot;,<br>  handleOrderCreated<br>);<br><br>// Later<br>unsubscribe();</pre><h3>One Event, Multiple Consumers</h3><p>The publisher never needs to know how many consumers exist.</p><pre>eventBus.on(<br>  &quot;ORDER_CREATED&quot;,<br>  updateOrderState<br>);<br><br>eventBus.on(<br>  &quot;ORDER_CREATED&quot;,<br>  showOrderNotification<br>);<br><br>eventBus.on(<br>  &quot;ORDER_CREATED&quot;,<br>  refreshOrderDashboard<br>);</pre><p>The message is published once:</p><pre>eventBus.emit(&quot;ORDER_CREATED&quot;, orderPayload);</pre><p>Each subscriber reacts independently.</p><p>A future analytics subscriber can be introduced without modifying the publisher or existing subscribers:</p><pre>eventBus.on(<br>  &quot;ORDER_CREATED&quot;,<br>  recordOrderAnalytics<br>);</pre><p>This is one of the central benefits of Pub/Sub.</p><h3>Why Not Use Redux for Everything?</h3><p>Redux remains an excellent tool for application state.</p><p>The Event Bus is not a replacement for Redux.</p><p>They solve different problems.</p><p>Redux answers questions such as:</p><ul><li>What is the current application state?</li><li>Which records have been loaded?</li><li>How many unread items exist?</li><li>Which filters are selected?</li><li>What state should React render?</li></ul><p>The Event Bus answers questions such as:</p><ul><li>What just happened?</li><li>Which parts of the application may need to react?</li><li>How can a transient event reach independent consumers?</li><li>How can one module announce an occurrence without importing another module?</li></ul><p>A useful boundary is:</p><pre>Event Bus<br>    Distributes occurrences<br><br>Redux<br>    Stores durable application state</pre><p>A subscriber may receive an event and then update Redux:</p><pre>eventBus.on(&quot;ORDER_CREATED&quot;, (message) =&gt; {<br>store.dispatch(  ordersSlice.actions.orderReceived(message.payload));<br>});</pre><p>The event remains transient. The resulting application state is stored in Redux.</p><p>This separation prevents the global state store from becoming a substitute for every form of communication.</p><h3>Layer 3: Defining Event Contracts</h3><p>Event-driven platforms can become difficult to maintain if events are arbitrary strings with undocumented payloads.</p><p>This is fragile:</p><pre>eventBus.emit(&quot;message&quot;, data);</pre><p>Months later, developers may not know:</p><ul><li>who publishes &quot;message&quot;;</li><li>what shape data has;</li><li>whether the event is still active;</li><li>which subscribers rely on it;</li><li>whether changing the payload will break another module.</li></ul><p>At minimum, event names should be centralised:</p><pre>export const Events = Object.freeze({<br>  ORDER_CREATED: &quot;ORDER_CREATED&quot;,<br>  ORDER_APPROVED: &quot;ORDER_APPROVED&quot;,<br>  DOCUMENT_PUBLISHED: &quot;DOCUMENT_PUBLISHED&quot;,<br>  NOTIFICATION_SELECTED: &quot;NOTIFICATION_SELECTED&quot;,<br>  CONNECTION_UNAVAILABLE: &quot;CONNECTION_UNAVAILABLE&quot;<br>});</pre><p>Publishers and consumers then use the same catalogue:</p><pre>eventBus.emit(Events.ORDER_CREATED, payload);<br>eventBus.on(  Events.ORDER_CREATED,  handleOrderCreated);</pre><p>This does not provide compile-time payload validation in JavaScript, but it removes scattered string literals and creates one discoverable event vocabulary.</p><h3>Introducing a Standard Event Envelope</h3><p>A consistent message envelope makes events easier to validate and evolve.</p><pre>const eventEnvelope = {<br>  id: crypto.randomUUID(),<br>  type: Events.ORDER_APPROVED,<br>  version: 1,<br>  timestamp: new Date().toISOString(),<br>  source: &quot;order-service&quot;,<br>  correlationId: &quot;workflow-123&quot;,<br>  payload: {<br>    orderId: &quot;ORD-1001&quot;,<br>    approvedBy: &quot;USER-42&quot;<br>  }<br>};</pre><p>Important fields may include:</p><ul><li>id: unique identity for deduplication or diagnostics;</li><li>type: event contract;</li><li>version: payload contract version;</li><li>timestamp: when the event was produced;</li><li>source: producing system or module;</li><li>correlationId: identifier shared by related workflow steps;</li><li>payload: event-specific data.</li></ul><p>Not every application needs every field immediately. A consistent envelope, however, provides room for future observability and compatibility.</p><h3>Runtime Validation</h3><p>JavaScript applications can add lightweight validation before distributing messages:</p><pre>function isValidEvent(message) {<br>  return Boolean(<br>    message &amp;&amp;<br>    typeof message === &quot;object&quot; &amp;&amp;<br>    typeof message.type === &quot;string&quot; &amp;&amp;<br>    message.type.trim()<br>  );<br>}</pre><p>The WebSocket bridge can reject invalid envelopes:</p><pre>if (!isValidEvent(message)) {<br>  console.warn(&quot;[Event] Invalid envelope&quot;, message);<br>  return;<br>}<br>eventBus.emit(message.type, message);</pre><p>For stronger validation, a schema-validation library can be used. The appropriate choice depends on the project’s dependency and governance requirements.</p><h3>Layer 4: React-Aware Event Listeners</h3><p>React components must subscribe and unsubscribe according to their lifecycle.</p><p>A reusable listener component can hide the Event Bus implementation:</p><pre>import { useEffect } from &quot;react&quot;;<br>import { eventBus } from &quot;./eventBus&quot;;<br><br>export function EventListener({<br>  eventType,<br>  onMessage<br>}) {<br>  useEffect(() =&gt; {<br>    if (!eventType || !onMessage) {<br>      return undefined;<br>    }<br><br>    const unsubscribe = eventBus.on(<br>      eventType,<br>      onMessage<br>    );<br><br>    return unsubscribe;<br>  }, [eventType, onMessage]);<br><br>  return null;<br>}</pre><p>A feature can then subscribe declaratively:</p><pre>function OrdersPage() {<br>  const handleOrderApproved = useCallback((event) =&gt; {<br>    console.log(<br>      &quot;Order approved&quot;,<br>      event.payload.orderId<br>    );<br>  }, []);<br><br>  return (<br>    &lt;&gt;<br>      &lt;EventListener<br>        eventType={Events.ORDER_APPROVED}<br>        onMessage={handleOrderApproved}<br>      /&gt;<br><br>      &lt;OrdersTable /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Using useCallback is important when the handler needs stable identity. If a new callback is created on every render, the effect must repeatedly unsubscribe and subscribe.</p><p>An alternative is a custom hook:</p><pre>import { useEffect } from &quot;react&quot;;<br>import { eventBus } from &quot;./eventBus&quot;;<br><br>export function useEvent(eventType, handler) {<br>  useEffect(() =&gt; {<br>    if (!eventType || !handler) {<br>      return undefined;<br>    }<br><br>    return eventBus.on(eventType, handler);<br>  }, [eventType, handler]);<br>}</pre><p>Usage:</p><pre>function Dashboard() {<br>  const handleDocumentPublished = useCallback(<br>    (event) =&gt; {<br>      refreshDashboard(event.payload);<br>    },<br>    []<br>  );<br><br>  useEvent(<br>    Events.DOCUMENT_PUBLISHED,<br>    handleDocumentPublished<br>  );<br><br>  return &lt;DashboardView /&gt;;<br>}</pre><h3>Global Listeners</h3><p>Some events affect the whole application rather than one screen.</p><p>A global listener can be mounted once near the application root:</p><pre>function GlobalEventListeners() {<br>  const dispatch = useDispatch();<br><br>  useEffect(() =&gt; {<br>    const handleOrderCreated = (event) =&gt; {<br>      dispatch(<br>        notificationsSlice.actions.addNotification({<br>          id: event.id,<br>          type: event.type,<br>          message: &quot;A new order was created&quot;,<br>          payload: event.payload,<br>          seen: false<br>        })<br>      );<br>    };<br><br>    const handleDocumentPublished = (event) =&gt; {<br>      dispatch(<br>        notificationsSlice.actions.addNotification({<br>          id: event.id,<br>          type: event.type,<br>          message: &quot;A document was published&quot;,<br>          payload: event.payload,<br>          seen: false<br>        })<br>      );<br>    };<br><br>    const unsubscribeOrder = eventBus.on(<br>      Events.ORDER_CREATED,<br>      handleOrderCreated<br>    );<br><br>    const unsubscribeDocument = eventBus.on(<br>      Events.DOCUMENT_PUBLISHED,<br>      handleDocumentPublished<br>    );<br><br>    return () =&gt; {<br>      unsubscribeOrder();<br>      unsubscribeDocument();<br>    };<br>  }, [dispatch]);<br><br>  return null;<br>}</pre><p>The application provider can initialise the connection and mount the global listeners:</p><pre>function RealTimeProvider({ children }) {<br>  useEffect(() =&gt; {<br>    webSocketManager.connect(<br>      configuration.realTimeUrl<br>    );<br><br>    return () =&gt; {<br>      webSocketManager.disconnectAll();<br>    };<br>  }, []);<br><br>  return (<br>    &lt;&gt;<br>      &lt;GlobalEventListeners /&gt;<br>      {children}<br>    &lt;/&gt;<br>  );<br>}</pre><p>The provider establishes infrastructure.</p><p>The listener translates selected events into application effects.</p><p>Feature modules remain unaware of the WebSocket connection.</p><h3>Why the Event Bus Was Not Enough</h3><p>The Event Bus solved distribution.</p><p>It did not automatically solve behaviour organisation.</p><p>As more event types were introduced, event-handling code could still become fragmented:</p><pre>if (event.type === &quot;ORDER_CREATED&quot;) {<br>  navigate(&quot;/orders&quot;);<br>}<br><br>if (event.type === &quot;DOCUMENT_PUBLISHED&quot;) {<br>  navigate(&quot;/documents&quot;);<br>}<br><br>if (event.type === &quot;USER_ASSIGNED&quot;) {<br>  navigate(&quot;/assignments&quot;);<br>}</pre><p>Similar conditions could appear in:</p><ul><li>notification rendering;</li><li>navigation handling;</li><li>acknowledgement logic;</li><li>state updates;</li><li>context resolution;</li><li>button labels;</li><li>workflow activation.</li></ul><p>The application had removed direct module dependencies, but event-specific behaviour was still scattered.</p><p>This led to the Registry Pattern.</p><h3>Layer 5: Registry-Based Workflow Resolution</h3><p>A registry maps an event type to its configuration.</p><pre>export const eventRegistry = {<br>  [Events.ORDER_CREATED]: {<br>    ui: {<br>      primaryActionLabel: &quot;View order&quot;,<br>      secondaryActionLabel: &quot;Mark as seen&quot;<br>    },<br><br>    behaviour: {<br>      openTarget: true,<br>      acknowledgeOnOpen: false<br>    },<br><br>    navigation: {<br>      pathname: &quot;/orders&quot;,<br>      getContext: (event) =&gt; ({<br>        orderId: event.payload?.orderId<br>      })<br>    }<br>  },<br><br>  [Events.DOCUMENT_PUBLISHED]: {<br>    ui: {<br>      primaryActionLabel: &quot;Open document&quot;,<br>      secondaryActionLabel: &quot;Dismiss&quot;<br>    },<br><br>    behaviour: {<br>      openTarget: true,<br>      acknowledgeOnOpen: true<br>    },<br><br>    navigation: {<br>      pathname: &quot;/documents&quot;,<br>      getContext: (event) =&gt; ({<br>        documentId: event.payload?.documentId<br>      })<br>    }<br>  }<br>};</pre><p>The registry separates configuration into logical groups:</p><h3>UI configuration</h3><p>Defines how an event is represented:</p><ul><li>primary action;</li><li>secondary action;</li><li>context visibility;</li><li>display metadata.</li></ul><h3>Behaviour configuration</h3><p>Defines workflow rules:</p><ul><li>whether an event opens a target;</li><li>whether it must be acknowledged;</li><li>whether another action must be dispatched;</li><li>whether related data must be refreshed.</li></ul><h3>Navigation configuration</h3><p>Defines:</p><ul><li>target route;</li><li>title or module identifier;</li><li>how workflow context is extracted from the event payload.</li></ul><h3>Resolving an Event</h3><p>A single resolver can now interpret registry configuration:</p><pre>function resolveEventAction({<br>  event,<br>  navigate,<br>  dispatch<br>}) {<br>  const config = eventRegistry[event.type];<br><br>  if (!config) {<br>    console.warn(<br>      &quot;[Registry] No configuration for event&quot;,<br>      event.type<br>    );<br><br>    return;<br>  }<br><br>  if (config.behaviour?.acknowledgeOnOpen) {<br>    dispatch(<br>      notificationsSlice.actions.markSeen(event.id)<br>    );<br>  }<br><br>  if (<br>    !config.behaviour?.openTarget ||<br>    !config.navigation<br>  ) {<br>    return;<br>  }<br><br>  const context =<br>    config.navigation.getContext?.(event) ?? {};<br><br>  navigate(config.navigation.pathname, {<br>    state: {<br>      source: &quot;real-time-event&quot;,<br>      context<br>    }<br>  });<br>}</pre><p>The notification component no longer needs event-specific conditions:</p><pre>function NotificationItem({ item }) {<br>  const navigate = useNavigate();<br>  const dispatch = useDispatch();<br><br>  const config = eventRegistry[item.type];<br><br>  if (!config) {<br>    return null;<br>  }<br><br>  return (<br>    &lt;article className=&quot;notification-item&quot;&gt;<br>      &lt;p&gt;{item.message}&lt;/p&gt;<br><br>      &lt;button<br>        onClick={() =&gt;<br>          resolveEventAction({<br>            event: item,<br>            navigate,<br>            dispatch<br>          })<br>        }<br>      &gt;<br>        {config.ui.primaryActionLabel}<br>      &lt;/button&gt;<br>    &lt;/article&gt;<br>  );<br>}</pre><p>A new event-driven workflow can often be introduced by:</p><ol><li>adding an event contract;</li><li>creating a registry entry;</li><li>adding a subscriber if custom behaviour is necessary;</li><li>implementing the target module.</li></ol><p>Existing transport and distribution infrastructure remains unchanged.</p><h3>Why the Registry Matters</h3><p>Without a registry:</p><pre>100 event types<br>      ↓<br>Conditions spread across components<br>      ↓<br>Multiple files modified for every workflow</pre><p>With a registry:</p><pre>100 event types<br>      ↓<br>Independent workflow definitions<br>      ↓<br>Shared resolvers and generic components</pre><p>The total business complexity does not disappear.</p><p>It becomes structured and discoverable.</p><p>That is an important distinction. Architecture cannot remove genuine domain complexity, but it can prevent that complexity from becoming accidental coupling.</p><h3>Complete Event Flow</h3><p>The end-to-end flow now looks like this:</p><pre>1. Server publishes an event<br>                ↓<br>2. WebSocket Manager receives the message<br>                ↓<br>3. Message envelope is parsed and validated<br>                ↓<br>4. Event Bus emits the event type and payload<br>                ↓<br>5. Global or module listeners react<br>                ↓<br>6. Application state is updated where required<br>                ↓<br>7. User selects an action<br>                ↓<br>8. Registry resolves behaviour and context<br>                ↓<br>9. Target module opens without direct coupling</pre><p>In code, the important boundaries are:</p><pre>// Transport<br>socket.onmessage = handleIncomingMessage;<br><br>// Distribution<br>eventBus.emit(message.type, message);<br><br>// Subscription<br>eventBus.on(Events.ORDER_CREATED, handler);<br><br>// Configuration<br>eventRegistry[Events.ORDER_CREATED];<br><br>// Business action<br>resolveEventAction({<br>  event,<br>  navigate,<br>  dispatch<br>});</pre><p>Each concern can evolve without forcing every other layer to change.</p><h3>Handling Acknowledgements</h3><p>Some real-time events require the client to notify the server when they have been seen or processed.</p><p>That can be expressed through the central manager:</p><pre>function acknowledgeEvent(event) {<br>  webSocketManager.send(configuration.realTimeUrl, {<br>    type: &quot;ACKNOWLEDGE_EVENT&quot;,<br>    eventId: event.id,<br>    acknowledgedAt: new Date().toISOString()<br>  });<br>}</pre><p>An optimistic state update may happen immediately:</p><pre>function markAsSeen(event, dispatch) {<br>  dispatch(<br>    notificationsSlice.actions.markSeen(event.id)<br>  );<br><br>  acknowledgeEvent(event);<br>}</pre><p>If acknowledgement is business-critical, the implementation should also define:</p><ul><li>failure behaviour;</li><li>retry policy;</li><li>idempotency;</li><li>server confirmation;</li><li>reconciliation after reconnect.</li></ul><p>For a non-critical visual seen-state, an optimistic update may be sufficient. For a consequential workflow transition, explicit confirmation is safer.</p><h3>Loading Historical Events</h3><p>WebSockets generally deliver new events. They do not necessarily restore messages missed while a user was offline.</p><p>A complete notification experience may therefore combine:</p><pre>HTTP<br>    Initial history and reconciliation<br><br>WebSocket<br>    New real-time events</pre><p>For example:</p><pre>async function initialiseNotifications(dispatch) {<br>  const historicalItems =<br>    await notificationApi.getNotifications();<br><br>  historicalItems.forEach((item) =&gt; {<br>    dispatch(<br>      notificationsSlice.actions.addNotification(item)<br>    );<br>  });<br>}</pre><p>The WebSocket connection then handles new events:</p><pre>eventBus.on(Events.ORDER_CREATED, (event) =&gt; {<br>  dispatch(<br>    notificationsSlice.actions.addNotification(event)<br>  );<br>});</pre><p>The server remains the source of truth.</p><p>The frontend store becomes the current user-interface representation.</p><p>This combination is usually more reliable than expecting the WebSocket channel to provide both event history and live delivery without an explicit protocol.</p><h3>Error Isolation</h3><p>One failing subscriber should not prevent other subscribers from processing the same event.</p><p>That is why each handler is invoked inside its own try/catch block:</p><pre>emit(eventType, payload) {<br>  const handlers = this.listeners.get(eventType);<br><br>  if (!handlers) {<br>    return;<br>  }<br><br>  [...handlers].forEach((handler) =&gt; {<br>    try {<br>      handler(payload);<br>    } catch (error) {<br>      console.error(<br>        `[EventBus] Failed handler for ${eventType}`,<br>        error<br>      );<br>    }<br>  });<br>}</pre><p>This provides basic isolation.</p><p>For important workflows, error reporting should capture more context:</p><pre>function reportHandlerFailure({<br>  eventType,<br>  eventId,<br>  error<br>}) {<br>  monitoring.captureException(error, {<br>    tags: {<br>      eventType<br>    },<br>    extra: {<br>      eventId<br>    }<br>  });<br>}</pre><p>A failed handler should be observable rather than silently ignored.</p><h3>Subscription Cleanup</h3><p>Missing cleanup can create:</p><ul><li>duplicate notifications;</li><li>handlers executing multiple times;</li><li>memory leaks;</li><li>behaviour triggered after a component has unmounted.</li></ul><p>This pattern is unsafe:</p><pre>useEffect(() =&gt; {<br>  eventBus.on(<br>    Events.ORDER_CREATED,<br>    handleOrderCreated<br>  );<br>}, []);</pre><p>The corrected pattern removes the exact same handler:</p><pre>useEffect(() =&gt; {<br>  eventBus.on(<br>    Events.ORDER_CREATED,<br>    handleOrderCreated<br>  );<br><br>  return () =&gt; {<br>    eventBus.off(<br>      Events.ORDER_CREATED,<br>      handleOrderCreated<br>    );<br>  };<br>}, [handleOrderCreated]);</pre><p>Returning an unsubscribe function makes this even cleaner:</p><pre>useEffect(() =&gt; {<br>  return eventBus.on(<br>    Events.ORDER_CREATED,<br>    handleOrderCreated<br>  );<br>}, [handleOrderCreated]);</pre><p>Lifecycle discipline is essential in event-driven React applications.</p><h3>Trade-Offs and Challenges</h3><p>This architecture improved modularity, but it also introduced costs.</p><h3>1. Event Flows Are Less Obvious</h3><p>A direct function call is easy to trace:</p><pre>Function A calls Function B</pre><p>With Pub/Sub:</p><pre>Module A emits an event<br>Several unknown subscribers react</pre><p>Developers need an event catalogue, naming conventions, and logging to understand the flow.</p><h3>2. Debugging Requires Better Observability</h3><p>Without structured logging, it can be difficult to answer:</p><ul><li>Was the event received?</li><li>Was it emitted?</li><li>Which subscribers were registered?</li><li>Which handler failed?</li><li>Was the event processed twice?</li><li>Which workflow produced it?</li></ul><p>Development-only diagnostics can help:</p><pre>emit(eventType, payload) {<br>  if (configuration.debugEvents) {<br>    console.debug(&quot;[EventBus] Emitting&quot;, {<br>      eventType,<br>      subscriberCount:<br>        this.listeners.get(eventType)?.size ?? 0,<br>      payload<br>    });<br>  }<br><br>  // Invoke handlers<br>}</pre><p>Sensitive payloads should not be logged indiscriminately. Logging policies must account for privacy, security, and production data handling.</p><h3>3. Event Explosion</h3><p>Without governance, event catalogues can become inconsistent:</p><pre>ORDER_CREATED<br>NEW_ORDER<br>ORDER_NEW<br>ORDER_RECEIVED</pre><p>A naming convention should be agreed early.</p><p>One possible convention is:</p><pre>domain.entity.action</pre><p>Examples:</p><pre>orders.order.created<br>documents.document.published<br>users.assignment.completed</pre><p>Another project may prefer uppercase constants. Consistency matters more than the particular format.</p><h3>4. Delivery Is Not Automatically Guaranteed</h3><p>A WebSocket message may be missed when:</p><ul><li>the browser is disconnected;</li><li>the tab is sleeping;</li><li>the network changes;</li><li>the server restarts;</li><li>reconnection attempts are exhausted.</li></ul><p>If an event is critical, the broader system needs concepts such as:</p><ul><li>server-side persistence;</li><li>sequence numbers;</li><li>acknowledgement;</li><li>replay;</li><li>reconciliation;</li><li>idempotent processing.</li></ul><p>A frontend Event Bus cannot create delivery guarantees that the server protocol does not provide.</p><h3>5. Ordering Can Matter</h3><p>Two events may arrive in an unexpected order:</p><pre>ORDER_UPDATED<br>ORDER_CREATED</pre><p>If ordering is important, the event protocol may require:</p><ul><li>sequence numbers;</li><li>version numbers;</li><li>timestamps;</li><li>server-side ordering;</li><li>client-side conflict resolution.</li></ul><p>The appropriate strategy depends on the business consequences.</p><h3>6. A Registry Can Become a New Monolith</h3><p>The registry solves scattered conditional logic, but an undisciplined registry can itself become too large.</p><p>Possible ways to split it include:</p><pre>const eventRegistry = {<br>  ...orderEventRegistry,<br>  ...documentEventRegistry,<br>  ...userEventRegistry<br>};</pre><p>Each domain owns its definitions while the platform composes them.</p><h3>7. Pub/Sub Can Be Overused</h3><p>Not every interaction requires an event.</p><p>Direct calls remain appropriate when:</p><ul><li>the caller requires an immediate return value;</li><li>one component explicitly owns another;</li><li>the relationship is simple and local;</li><li>command execution must be synchronous and obvious.</li></ul><p>Events are best suited to announcements:</p><blockquote><em>Something happened. Interested consumers may respond.</em></blockquote><p>They are less suitable for disguised request-response interactions.</p><h3>Benefits of the Architecture</h3><h3>Reduced Module Coupling</h3><p>Publishers and subscribers depend on event contracts rather than on each other’s implementations.</p><h3>Centralised Connection Management</h3><p>Authentication, heartbeat, reconnection, sending, cleanup, and socket tracking are handled in one place.</p><h3>Reusable Real-Time Infrastructure</h3><p>New modules can consume events without creating new WebSocket implementations.</p><h3>Cleaner Separation of Concerns</h3><pre>WebSocket Manager<br>    Receives and sends messages<br><br>Event Bus<br>    Distributes occurrences<br><br>Registry<br>    Resolves workflow configuration<br><br>Redux or another store<br>    Maintains application state<br><br>React Components<br>    Render the interface<br><br>Business Modules<br>    Execute domain behaviour</pre><h3>Easier Workflow Extension</h3><p>A new workflow can frequently be introduced by adding an event contract, registry definition, and subscriber rather than modifying multiple unrelated modules.</p><h3>Lower Regression Surface</h3><p>Existing transport and shared distribution code does not need to change for every new event type.</p><p>This does not eliminate regression risk, but it reduces unnecessary changes to stable infrastructure.</p><h3>Improved Discoverability</h3><p>A central event catalogue and domain-based registry give developers explicit locations for understanding system behaviour.</p><h3>What I Would Improve Next</h3><p>The implementation described here provides a practical foundation. Several improvements would make it more robust.</p><h3>1. Type-Safe Event Contracts</h3><p>TypeScript can associate each event with its payload:</p><pre>type EventMap = {<br>  ORDER_CREATED: {<br>    id: string;<br>    orderId: string;<br>  };<br><br>  DOCUMENT_PUBLISHED: {<br>    id: string;<br>    documentId: string;<br>  };<br><br>  CONNECTION_UNAVAILABLE: {<br>    url: string;<br>    attempts: number;<br>  };<br>};</pre><p>If I were implementing this today I would likely leverage TypeScript event maps to achieve compile-time enforcement of event contracts and payloads.</p><p>Now this is valid:</p><pre>eventBus.emit(&quot;ORDER_CREATED&quot;, {<br>  id: &quot;event-1&quot;,<br>  orderId: &quot;order-42&quot;<br>});</pre><p>And an invalid payload can be detected during development.</p><h3>2. Event Versioning</h3><p>Contracts evolve.</p><p>Adding a version allows consumers to handle compatibility explicitly:</p><pre>{<br>  &quot;type&quot;: &quot;ORDER_CREATED&quot;,<br>  &quot;version&quot;: 2,<br>  &quot;payload&quot;: {<br>    &quot;orderId&quot;: &quot;order-42&quot;<br>  }<br>}</pre><p>A version-aware resolver could route accordingly:</p><pre>const eventKey =  `${event.type}:v${event.version ?? 1}`;<br><br>const handler = versionedRegistry[eventKey];</pre><p>Versioning should not be introduced casually, but it becomes important when publishers and consumers evolve independently.</p><h3>3. Correlation IDs</h3><p>A workflow may generate several related events.</p><pre>ORDER_CREATED<br>      ↓<br>PAYMENT_REQUESTED<br>      ↓<br>PAYMENT_COMPLETED<br>      ↓<br>ORDER_CONFIRMED</pre><p>A shared correlation ID supports end-to-end tracing:</p><pre>{<br>  &quot;id&quot;: &quot;event-103&quot;,<br>  &quot;type&quot;: &quot;PAYMENT_COMPLETED&quot;,<br>  &quot;correlationId&quot;: &quot;order-workflow-42&quot;,<br>  &quot;payload&quot;: {}<br>}</pre><p>This makes diagnostics significantly easier across frontend and backend systems.</p><h3>4. Observability</h3><p>Useful metrics may include:</p><ul><li>received event count;</li><li>event processing latency;</li><li>handler failures;</li><li>number of active subscriptions;</li><li>reconnect attempts;</li><li>disconnected duration;</li><li>unknown event types;</li><li>duplicate event IDs.</li></ul><p>The precise metrics depend on operational needs, but the architecture should provide observable boundaries.</p><h3>5. Deduplication</h3><p>If the server retries an event or the client reconnects and receives replayed messages, the same event may arrive more than once.</p><p>A small processed-event cache can provide limited client-side protection:</p><pre>class EventDeduplicator {<br>  constructor(limit = 500) {<br>    this.limit = limit;<br>    this.processedIds = new Set();<br>  }<br><br>  hasProcessed(eventId) {<br>    return this.processedIds.has(eventId);<br>  }<br><br>  markProcessed(eventId) {<br>    this.processedIds.add(eventId);<br><br>    if (this.processedIds.size &gt; this.limit) {<br>      const oldestId =<br>        this.processedIds.values().next().value;<br><br>      this.processedIds.delete(oldestId);<br>    }<br>  }<br>}</pre><p>Client-side deduplication can help interface behaviour, but server-side idempotency remains necessary for consequential operations.</p><h3>6. Testing Strategy</h3><p>Each layer can be tested independently.</p><h3>Event Bus test</h3><pre>it(&quot;notifies all subscribers&quot;, () =&gt; {<br>  const bus = new EventBus();<br><br>  const firstHandler = vi.fn();<br>  const secondHandler = vi.fn();<br><br>  bus.on(&quot;TEST_EVENT&quot;, firstHandler);<br>  bus.on(&quot;TEST_EVENT&quot;, secondHandler);<br><br>  bus.emit(&quot;TEST_EVENT&quot;, {<br>    value: 42<br>  });<br><br>  expect(firstHandler).toHaveBeenCalledWith({<br>    value: 42<br>  });<br><br>  expect(secondHandler).toHaveBeenCalledWith({<br>    value: 42<br>  });<br>});</pre><h3>Unsubscription test</h3><pre>it(&quot;does not notify an unsubscribed handler&quot;, () =&gt; {<br>  const bus = new EventBus();<br>  const handler = vi.fn();<br><br>  const unsubscribe = bus.on(<br>    &quot;TEST_EVENT&quot;,<br>    handler<br>  );<br><br>  unsubscribe();<br><br>  bus.emit(&quot;TEST_EVENT&quot;, {});<br><br>  expect(handler).not.toHaveBeenCalled();<br>});</pre><h3>Registry resolution test</h3><pre>it(&quot;extracts navigation context&quot;, () =&gt; {<br>  const event = {<br>    type: Events.ORDER_CREATED,<br>    payload: {<br>      orderId: &quot;order-42&quot;<br>    }<br>  };<br><br>  const config =<br>    eventRegistry[event.type];<br><br>  expect(<br>    config.navigation.getContext(event)<br>  ).toEqual({<br>    orderId: &quot;order-42&quot;<br>  });<br>});</pre><p>WebSocket routing test</p><p>The WebSocket manager can be tested with a mocked WebSocket implementation, verifying that a received event is forwarded to the Event Bus without invoking business logic directly.</p><p>The architecture’s separation of concerns makes isolated testing easier.</p><h3>When This Architecture Is Appropriate</h3><p>This design can be valuable when an application has:</p><ul><li>several independently evolving modules;</li><li>multiple consumers for the same events;</li><li>real-time server communication;</li><li>cross-module workflows;</li><li>registry-driven navigation or actions;</li><li>repeated event-handling patterns;</li><li>a need to isolate transport from features.</li></ul><p>It may be unnecessary for:</p><ul><li>a small single-purpose application;</li><li>a handful of local component interactions;</li><li>simple parent-child communication;</li><li>workflows with no real-time behaviour;</li><li>applications where one state store already provides a clear and sufficient model.</li></ul><p>Architecture should be proportional to actual complexity.</p><p>Introducing an Event Bus and registry before the need exists may create more indirection than value.</p><h3>Final Thoughts</h3><p>The most important lesson was not about React.</p><p>It was not about WebSockets.</p><p>It was not even about notifications.</p><p>The key lesson was this:</p><blockquote><em>Communication in a large frontend application should be treated as infrastructure when multiple independent modules need to respond to the same evolving set of events.</em></blockquote><p>WebSockets provided real-time transport.</p><p>The Event Bus separated transport from consumers.</p><p>Event contracts created a shared vocabulary.</p><p>React listeners connected events to component lifecycles.</p><p>The registry moved workflow behaviour out of scattered conditional logic.</p><p>Together, these layers transformed the architecture from:</p><pre>WebSocket<br>↓<br>Feature-specific logic</pre><p>into:</p><pre>WebSocket Manager<br>↓<br>Event Bus<br>↓<br>Event Contracts<br>↓<br>Listeners and Registry<br>↓<br>Independent Business Modules</pre><p>The value did not come from using several design patterns for their own sake.</p><p>The value came from assigning each problem to the correct layer:</p><ul><li>connection reliability belongs to the transport manager;</li><li>distribution belongs to the Event Bus;</li><li>communication vocabulary belongs to event contracts;</li><li>workflow configuration belongs to the registry;</li><li>application state belongs to the state-management layer;</li><li>business decisions belong to the relevant modules.</li></ul><p>Once those boundaries were established, new real-time workflows became easier to add without repeatedly changing stable infrastructure or creating direct dependencies between modules.</p><p>That is the real shift:</p><blockquote><em>Real-time communication stops being a feature-specific integration and becomes a reusable frontend platform capability.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77a80078cc2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>