<?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 Sushmitha Dhummi Thrilochana on Medium]]></title>
        <description><![CDATA[Stories by Sushmitha Dhummi Thrilochana on Medium]]></description>
        <link>https://medium.com/@sushmita.dt?source=rss-29613658adba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*13wdWucbNVVQODjvUwRzUw.jpeg</url>
            <title>Stories by Sushmitha Dhummi Thrilochana on Medium</title>
            <link>https://medium.com/@sushmita.dt?source=rss-29613658adba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 06:02:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sushmita.dt/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[Real-Time Events: Choosing the Right Tool for the Right Problem]]></title>
            <link>https://medium.com/@sushmita.dt/real-time-events-choosing-the-right-tool-for-the-right-problem-01db1cf7833a?source=rss-29613658adba------2</link>
            <guid isPermaLink="false">https://medium.com/p/01db1cf7833a</guid>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[kd]]></category>
            <category><![CDATA[cloud-services]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Sushmitha Dhummi Thrilochana]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 00:39:53 GMT</pubDate>
            <atom:updated>2026-10-06T00:39:53.949Z</atom:updated>
            <content:encoded><![CDATA[<p>“Real-time” is not one problem. It is several, and each one has a different cheapest correct answer. A typing indicator, a kitchen ticket, a card charge and a clickstream all feel “live”, but they differ in what happens when a message is lost, duplicated or late. Choosing tools well starts with naming which problem you have.</p><p>The running example is a restaurant Kitchen Display System (KDS). A guest orders from a QR menu, the order reaches the kitchen screen, cooks move it through statuses, and the guest sees “Ready”. That one feature turns out to contain three different real-time problems: syncing ticket state, alerting a cook to a new order, and printing a ticket exactly once.</p><p>The article builds a vocabulary in four steps: the layers of a real-time system, the categories of real-time data, the questions that classify a feature, and the tools and cost models that fit each category. It ends with worked cases and a script for system design interviews.</p><h3>The three layers of a real-time system</h3><p>Most confusion comes from comparing tools that live in different layers. Separate them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPVBJCwG1tanZ2F0O4D7_Q.png" /></figure><ul><li><strong>Source of truth (server, storage):</strong> where the data lives and where guarantees such as ACID transactions are enforced.</li><li><strong>Backbone (server ⇄ server):</strong> carries the news of a change from the server that made it to every server holding interested clients.</li><li><strong>Transport (server ⇄ client):</strong> the last mile from a server to a screen.</li></ul><p>So “SSE vs. Redis” is a category error: SSE is a transport, Redis is a backbone. You often use both.</p><p>Managed products <strong>bundle layers</strong>, which is why comparing them is confusing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QfNnhGmLmpMKtz-FAhfzvA.png" /></figure><p>When you compare two products, first check they cover the same layers. Firestore versus Kafka is not a fair fight; Firestore versus Pusher plus Postgres is.</p><h3>The six categories of real-time data</h3><p>This is the core distinction. For any feature, first identify which category it is.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_HWM8-V6gSzeduTwee462g.png" /></figure><h4>A. State sync: “show me the current value”</h4><p><em>Examples:</em> KDS tickets, order status, dashboards, inventory counts, ride status, seat availability.</p><ul><li><strong>Defining property:</strong> the latest value supersedes earlier ones. Intermediate updates don’t matter if missed.</li><li><strong>Pattern:</strong> <strong>snapshot + deltas</strong>. On connect, send current state; then send changes. On reconnect, resend the snapshot.</li><li><strong>Loss tolerance:</strong> high, because a resync fixes everything.</li><li><strong>Good tools:</strong> Firestore, Supabase Realtime, SSE + snapshot, even <strong>polling</strong> if latency of a few seconds is fine.</li></ul><h4>B. Ephemeral signals: “worthless a second later”</h4><p><em>Examples:</em> typing indicators, cursor positions, live driver location, game player positions, “user is viewing.”</p><ul><li><strong>Defining property:</strong> high frequency and short-lived; stale data is useless.</li><li><strong>Pattern:</strong> fire-and-forget, <strong>throttle/conflate</strong> (send only the latest value per key every N ms), never store.</li><li><strong>Loss tolerance:</strong> total; the next update replaces it.</li><li><strong>Good tools:</strong> WebSocket + Redis pub/sub, Pusher/Ably, WebRTC for peer-to-peer.</li><li><strong>Bad fit:</strong> a database. You’d pay for and store millions of values nobody will read.</li></ul><h4>C. Discrete messages: “each one matters, the user must eventually see it”</h4><p><em>Examples:</em> chat messages, comments, alerts, “new order” notifications.</p><ul><li><strong>Defining property:</strong> each message has individual value; missing one is a bug.</li><li><strong>Pattern:</strong> <strong>persist first, then deliver.</strong> Write to the database, push over WebSocket/SSE as an optimization, and the client <strong>catches up</strong> via a history API (messages after id X) on reconnect. Use sequence numbers or IDs for gap detection and dedupe.</li><li><strong>Offline users:</strong> add <strong>push notifications</strong> (APNs, FCM, Web Push).</li><li><strong>Good tools:</strong> DB + WebSocket + Redis fan-out; Firestore; Ably/Pusher with history.</li></ul><h4>D. Commands / work: “must happen, effectively once”</h4><p><em>Examples:</em> charge a card, send a receipt email, print a kitchen ticket, decrement inventory, call a delivery partner’s API.</p><ul><li><strong>Defining property:</strong> a side effect in the world. Missing it or doing it twice both cause damage.</li><li><strong>Pattern:</strong> <strong>durable queue + at-least-once delivery + idempotent consumers</strong>, with retries and a <strong>dead-letter queue</strong>. Use the <strong>outbox pattern</strong> to publish reliably from a database transaction.</li><li><strong>Good tools:</strong> SQS, Google Pub/Sub, RabbitMQ, Kafka, Redis Streams.</li><li><strong>Note:</strong> this often isn’t user-facing “real-time” at all, but candidates mix it up with category A. Interviewers notice.</li></ul><h4>E. High-throughput streams: “ordered, replayable, many consumers”</h4><p><em>Examples:</em> clickstream analytics, IoT telemetry, logs/metrics, activity feeds, CDC pipelines.</p><ul><li><strong>Defining property:</strong> huge volume; several independent consumers (analytics, search indexing, ML) each read at their own pace; replay needed.</li><li><strong>Pattern:</strong> append-only <strong>log</strong>, partitioned by key for ordering, consumer offsets, retention.</li><li><strong>Good tools:</strong> Kafka, Kinesis, Pub/Sub, Redpanda.</li></ul><h4>F. Collaborative shared state: “many people editing the same thing”</h4><p><em>Examples:</em> Google Docs, Figma, multiplayer whiteboards.</p><ul><li><strong>Defining property:</strong> concurrent edits must merge without conflicts.</li><li><strong>Pattern:</strong> <strong>OT</strong> (operational transformation) or <strong>CRDTs</strong>, usually over WebSocket, with a sync server.</li><li><strong>Good tools:</strong> Yjs, Automerge, Liveblocks. This is a specialized category; name it and say it needs conflict resolution, not just pub/sub.</li></ul><p><em>Bonus: live audio/video is its own world: WebRTC for low-latency calls, HLS/DASH via CDN for broadcast.</em></p><p><strong>Most features mix categories.</strong> A KDS is mostly state sync (A), but its “new order” alert behaves like a discrete message ©, and ticket printing is work (D). Good designs give each part its own tool.</p><h3>The questions that sort a feature into a category</h3><p>In an interview, ask these out loud. That alone signals seniority.</p><ol><li><strong>Does the newest value replace older ones?</strong> Yes → state sync (A) or ephemeral (B). No → messages © or work (D).</li><li><strong>What happens if one update is lost?</strong> Nothing → B. Resync fixes it → A. User misses something → C. Real-world damage → D.</li><li><strong>Delivery guarantee needed?</strong> At-most-once (B), at-least-once + resync (A, C), effectively-once via idempotency (D). “Exactly-once” is generally achieved as at-least-once + idempotency; say that explicitly.</li><li><strong>Ordering?</strong> None, <strong>per key</strong> (per order, per chat room; the most common answer), or global (rare and expensive).</li><li><strong>Direction and frequency?</strong> Server → client only → SSE is enough. Frequent client → server too → WebSocket.</li><li><strong>Fan-out shape?</strong> 1:1 (your ride), 1:small-N (a restaurant’s screens), 1:millions (live sports score), N:N (chat room, game).</li><li><strong>Latency budget?</strong> Under 100 ms (games, cursors), under 1 s (KDS, chat), several seconds (dashboards; polling may be the cheapest correct answer).</li><li><strong>Must offline users get it?</strong> Yes → persistence + push notifications.</li><li><strong>How many concurrent connections, and how idle?</strong> This decides the cost model (see Cost models below).</li></ol><p>The first two questions usually settle the category. The rest settle the design.</p><h3>Transport comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mM9GCZhDITNnkW0WCCj_LA.png" /></figure><p>Good interview line: <em>“Server-to-client only, so SSE is enough. Client actions go over regular REST. I’d only reach for WebSockets if clients were sending frequent messages.”</em></p><h4>How SSE works</h4><p>SSE (“Server-Sent Events”) is a long-lived HTTP response:</p><ol><li>The KDS opens a normal HTTP GET with Accept: text/event-stream.</li><li>The server responds 200 OK with Content-Type: text/event-stream, but <strong>never finishes the response</strong>. The connection stays open.</li><li>Whenever something happens, the server writes a small chunk into that still-open response. The browser’s EventSource fires an event in JavaScript for each chunk.</li><li>Between orders, nothing is sent except maybe an occasional heartbeat (: ping) so proxies don&#39;t treat the connection as dead.</li><li>If the connection drops, the browser reconnects and the cycle repeats.</li></ol><p>The request:</p><pre>GET /kitchen/42/stream<br>Accept: text/event-stream</pre><p>A chunk the server writes when an order arrives:</p><pre>event: order.created<br>data: {&quot;id&quot;: 981, &quot;table&quot;: 7, &quot;items&quot;: [...]}</pre><p>So for a KDS screen open all evening, that is <strong>one request lasting hours</strong>, mostly idle and waiting.</p><p>A minimal FastAPI endpoint:</p><pre>@app.get(&quot;/kitchen/{rid}/stream&quot;)<br>async def stream(rid: int, request: Request):<br>    async def events():<br>        yield f&quot;event: snapshot\ndata: {json.dumps(await active_orders(rid))}\n\n&quot;<br>        async for evt in order_bus.subscribe(rid):        # fed by LISTEN/NOTIFY<br>            if await request.is_disconnected(): break<br>            yield f&quot;id: {evt.id}\nevent: {evt.type}\ndata: {evt.json}\n\n&quot;<br>    return StreamingResponse(events(), media_type=&quot;text/event-stream&quot;)</pre><p>Sending a full snapshot first, then deltas, means every reconnect self-heals. Tagging each event with id: lets the browser send Last-Event-ID when it reconnects, so the server can resume where it left off.</p><p>Two practical quirks: EventSource can&#39;t send an Authorization header, so use a cookie, a short-lived token in the URL, or a library such as fetch-event-source. And load balancers often close idle connections after 30 to 60 seconds by default, so send heartbeats and raise the timeout.</p><h4>The SSE-on-serverless trap</h4><p>The short version: <strong>Cloud Run bills by how long a request is open, not by how much work your code does.</strong> An SSE stream is a single request that stays open for hours.</p><p>In the default (request-based) mode, Cloud Run charges for <strong>CPU and memory for every moment an instance has at least one request in progress</strong>, rounded to 100 ms. It doesn’t measure whether your code is actually using the CPU; “request open” equals “billed.”</p><p>That works out very cheaply for normal REST:</p><pre>REST:  an order request takes ~80 ms<br>time ─────────────────────────────────────────────────────────►<br>billed  ▌        ▌    ▌             ▌      ▌            ▌<br>        (tiny slivers; instance scales to zero in between)</pre><p>But not for SSE:</p><pre>SSE:   KDS stream open from 11:00 to 23:00<br>time ─────────────────────────────────────────────────────────►<br>billed  ████████████████████████████████████████████████████████<br>        (request never ends → billed the whole time,<br>         even though the CPU is idle 99.9% of it)</pre><p>Two effects combine:</p><ul><li><strong>The meter never stops.</strong> From Cloud Run’s point of view, the instance is busy serving a request for the whole shift.</li><li><strong>No scale-to-zero.</strong> Since a request is always open, the instance can’t shut down between orders.</li></ul><p>The 60-minute request timeout doesn’t help: the stream gets cut, EventSource reconnects within seconds, and billing continues.</p><p><strong>So while the KDS is connected, the backend can’t shut down.</strong> The KDS opens one SSE request when the screen loads and holds it open, listening rather than asking “anything new?”. As long as that request is open, Cloud Run counts the instance as busy, so it won’t scale that instance to zero and keeps billing, even while the code sits in await waiting for the next order. Some nuances:</p><ul><li><strong>It’s not guaranteed to stay up forever.</strong> Cloud Run still ends the stream at the request timeout (max 60 minutes), on a new deployment, or occasionally for maintenance. The KDS reconnects within a few seconds, possibly to a fresh instance, which is why the stream starts with a snapshot of active orders.</li><li><strong>The instance isn’t doing work while waiting.</strong> CPU usage is near zero; you’re paying for it being <em>reserved</em>, not <em>used</em>.</li><li><strong>Other traffic shares it.</strong> Customer orders and admin API calls can be served by that same already-running instance (up to its concurrency limit), so you aren’t paying twice for them during service hours.</li></ul><p><strong>The math (ballpark).</strong> Assume a KDS open 12 hours/day, 30 days/month, on a 1 vCPU / 512 MiB instance. These are list prices at the time of writing; check the current Cloud Run pricing page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LLm1rp2q-xLZCZ-Q-Lqw4g.png" /></figure><p>That’s roughly <strong>$25–30/month</strong>. The same KDS on Firestore listeners costs about <strong>$0</strong>, and even 1,000 API calls/day × 100 ms is only about 3,000 billed seconds per month.</p><p><strong>What doesn’t make it worse:</strong> overlapping streams on the same instance are billed once. Billing is per instance-time, not per connection. Three KDS tablets plus 40 customer status pages all held by one instance cost about the same as one tablet. Cost grows with the <strong>hours instances stay alive</strong> (and with more instances if you scale out), not with the number of screens.</p><p>SSE itself is lightweight. It’s the per-request billing model that makes long-lived connections expensive.</p><h3>Backbones: is the bus a post office?</h3><p>Partly. The post-office analogy fits the <strong>routing</strong> part well, but whether it <em>ensures delivery</em> depends on which kind of bus you use.</p><p><strong>Where the analogy fits: addressing and decoupling</strong></p><ul><li>The API (the sender) doesn’t need to know which gateway server a KDS tablet is connected to. It just “mails” the event to an address like restaurant:42:kitchen.</li><li>The bus routes it to whoever is subscribed to that address, on any gateway node.</li><li>Senders and receivers never talk directly, so either side can scale, restart, or move independently.</li></ul><p><strong>Where it differs: delivery guarantees.</strong> There are two kinds of bus, plus a third way to get change events:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGoYC0w5xvPsqVRrsTgztw.png" /></figure><p><strong>Even a real post office only delivers to the gateway.</strong> The last hop, gateway → browser over SSE, can still drop: tablet Wi-Fi blips, the connection is cut mid-event. No bus can guarantee that hop. That’s why the <strong>snapshot-on-connect</strong> (plus Last-Event-ID resume) pattern matters: when the KDS reconnects, it gets the current state, so it doesn&#39;t matter what was missed.</p><p><strong>For a KDS, the loudspeaker kind is enough.</strong> Postgres LISTEN/NOTIFY or Redis pub/sub work because <strong>Postgres is the permanent record</strong>: the bus only exists to say &quot;something changed, update now,&quot; and if an announcement is missed, the snapshot on reconnect plus a periodic resync covers it. You&#39;d want the post-office kind for work that must happen exactly once and has no other record: sending a receipt email, charging a card, syncing to an accounting system, or triggering a printer job.</p><h4>Choosing a bus: Redis, Kafka, or Google Pub/Sub</h4><p><strong>Redis is a good fit.</strong> Redis pub/sub is the classic choice for a realtime gateway: tiny latency (sub-millisecond), simple API, and every gateway node can subscribe to the channels it needs.</p><pre># API: publish after the Postgres commit<br>await redis.publish(f&quot;restaurant:{rid}:kitchen&quot;, json.dumps(<br>    {&quot;type&quot;: &quot;order.created&quot;, &quot;order_id&quot;: order.id}))</pre><pre># Gateway: subscribe and forward to SSE clients<br>pubsub = redis.pubsub()<br>await pubsub.psubscribe(&quot;restaurant:*:kitchen&quot;)<br>async for msg in pubsub.listen():<br>    if msg[&quot;type&quot;] == &quot;pmessage&quot;:<br>        forward_to_sse_clients(msg[&quot;channel&quot;], msg[&quot;data&quot;])</pre><ul><li>Plain Redis pub/sub is the “loudspeaker” type (no storage). If you want “post office” behavior, <strong>Redis Streams</strong> with consumer groups adds persistence and acknowledgements on the same Redis.</li><li><strong>One difference from Postgres </strong><strong>NOTIFY:</strong> publishing to Redis is a separate step after the Postgres commit, so a small dual-write gap returns. A crash between commit and publish means no announcement. For a KDS that&#39;s fine because of the snapshot and resync. NOTIFY avoids the gap because it&#39;s sent inside the transaction, but it needs a direct, non-pooled Postgres connection (transaction poolers like PgBouncer don&#39;t support LISTEN).</li><li>Cheap options: a serverless Redis with a free tier (such as Upstash), or Redis on the same small VM as the gateway. Managed in-network Redis (such as Google Memorystore) bills per hour even when idle.</li></ul><p><strong>Kafka is overkill for this.</strong> Kafka is a <strong>durable, replayable log</strong> built for huge throughput: millions of events per second, event sourcing, analytics pipelines, feeding many downstream systems.</p><ul><li><strong>Heavy to run:</strong> clusters, partitions, retention, consumer offsets. A lot of machinery for a few hundred orders per day.</li><li><strong>Not built for this fan-out pattern:</strong> dynamic per-restaurant channels with short-lived subscribers fit Redis better.</li><li>Its exactly-once semantics apply inside Kafka (producer → topic → consumer with transactions); end to end you still need idempotent consumers.</li><li>It makes sense when you build analytics pipelines, an event-sourced order history, or integrations that need to replay events.</li></ul><p><strong>Google Pub/Sub for must-happen work.</strong> It’s durable (the post-office kind), has a free tier, and needs no servers. A good choice for receipt emails, payment webhooks, printer jobs, and syncing to accounting tools. For live KDS fan-out it’s heavier than Redis.</p><p><strong>A sensible ranking for a small app:</strong></p><ol><li><strong>Postgres </strong><strong>LISTEN/NOTIFY:</strong> no new infrastructure and transactional, if a direct connection is available.</li><li><strong>Redis:</strong> the most common choice, and it scales further.</li><li><strong>Google Pub/Sub (or SQS):</strong> alongside either of the above, for durable background jobs.</li><li><strong>Kafka:</strong> only when you have a real data-pipeline or event-sourcing need.</li></ol><h3>Using a database for real-time events</h3><p>It can feel counterintuitive and hacky to use a database for real-time events. That instinct is partly right. It depends on whether you see the feature as <strong>sending messages</strong> or <strong>syncing state</strong>.</p><p><strong>Firestore wasn’t hacked into doing real-time; that’s what it was built for.</strong> Its headline feature since launch has been “sync data to clients live,” and under the hood the listener system is the main product. Watching a database for changes and pushing them to clients is also a standard pattern:</p><ul><li><strong>Supabase Realtime</strong> streams Postgres changes to browsers.</li><li><strong>MongoDB change streams</strong> and <strong>RethinkDB changefeeds</strong> let you subscribe to a query or collection.</li><li><strong>CDC (change data capture)</strong> with tools like Debezium reads the database’s own change log and publishes it to Kafka. Many large companies drive their event systems this way.</li><li><strong>Postgres </strong><strong>LISTEN/NOTIFY</strong> is the database itself acting as the bus.</li><li>Even <strong>Kafka</strong> is essentially a durable, append-only log, which is very close to a database.</li></ul><p><strong>A KDS is really a state-sync problem.</strong> The question the screen answers is “what are the open tickets right now?”, not “deliver me message #4,812.” Syncing state from a database fits that better than a message stream: missed updates fix themselves, reconnects just reload the current state, and there’s no event replay logic to write.</p><p><strong>Where the instinct is right:</strong></p><ul><li><strong>Using a database for short-lived, high-frequency events</strong> (typing indicators, cursor positions, “table 7 is browsing the menu”) is a poor fit. Every event becomes a stored, billed write that you then have to clean up. A pure messaging system (Pusher/Ably, Redis pub/sub) suits those better.</li><li><strong>Copying data into a second database just to get real-time</strong> is the genuinely awkward part. That dual write is a workaround, which is why SSE + Postgres NOTIFY or Supabase Realtime (events coming from your <em>one</em> source of truth) feel cleaner.</li></ul><h4>Three ways to use Firestore for events</h4><p><strong>1. As the bus and the gateway together.</strong> The API writes to Firestore (publish), Google holds the connections (bus + gateway), and screens subscribe directly. You don’t need Redis or an SSE gateway in front of it. Putting Firestore <em>behind</em> an SSE gateway would only add a hop; use one or the other.</p><p><strong>2. State documents vs. event documents.</strong></p><ul><li><strong>State docs</strong> (recommended for a KDS): one doc per order, updated in place, such as restaurants/42/orders/981 { status: &quot;preparing&quot;, items: [...] }. The screen always renders the <strong>current state</strong>; missed updates don&#39;t matter because the listener resyncs to the latest version.</li><li><strong>Event docs</strong> (an append-only log): one new doc per event, such as restaurants/42/events/{auto-id} { type: &quot;order.status_changed&quot;, orderId: 981, status: &quot;ready&quot; }. Upsides: a durable history you can replay with where(&quot;at&quot;, &quot;&gt;&quot;, lastSeen), closer to Redis Streams or Pub/Sub. Downsides: more reads and writes, clients must rebuild state from events, timestamp ordering is approximate when events land close together, and you need a <strong>TTL policy</strong> to clean old events.</li><li>Event docs make sense for one-off signals that have no “state,” such as “table 7 called the waiter,” “play the new-order chime,” or an audit trail.</li></ul><p><strong>3. As a backend event bus (triggers).</strong> Firestore writes can trigger Cloud Functions (onDocumentCreated, onDocumentUpdated): an order turning &quot;ready&quot; can send an SMS, a new order can print a ticket. Delivery is <strong>at-least-once</strong>, so a function can occasionally run twice; make handlers idempotent. It&#39;s convenient but ties more logic to Firebase; a Postgres outbox → Pub/Sub does the same job more portably.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YstLGllMw5iZPWrsrKEYeA.png" /></figure><h4>The AWS equivalents</h4><p>Firestore is roughly <strong>DynamoDB + AppSync subscriptions + Cognito-scoped client access</strong>, bundled into one product. On AWS, <strong>Amplify Data</strong> ties those together into a Firebase-like experience (define a model; the frontend reads, writes and subscribes directly). For plain pub/sub without the data layer there is <strong>AppSync Events</strong>, a managed WebSocket channel service, the AWS counterpart to using Firestore purely as a live feed. Getting new orders onto a screen with raw DynamoDB means wiring DynamoDB Streams → Lambda → AppSync or API Gateway WebSockets yourself.</p><h3>The order versus the notification: where guarantees live</h3><p>A KDS has a “new order” notification where each order is important and must be executed only once. It’s tempting to conclude that Kafka or Redis leaves the least room for error, or that in a perfect world everything would be SQL and ACID. The answer is to separate <strong>the order</strong> from <strong>the notification about the order</strong>. Once you split those, the trade-off becomes clear.</p><h4>1. Two different things need different guarantees</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fI5LDaVIIJ0H8lzNdvn2dQ.png" /></figure><p>“Each order must be executed exactly once” is a guarantee on the <strong>order’s state</strong>, not on the <strong>message pipe</strong>. The cook starting the order once is enforced by the order’s status in the database, not by how many times a notification arrived.</p><h4>2. Why Kafka or Redis doesn’t remove the room for error</h4><p>Follow the path of one order and see where things can fail:</p><pre>POST /orders → [1] Postgres commit → [2] publish → [3] bus → [4] gateway → [5] SSE to tablet → [6] cook sees it</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPb7p9OR4CmVkYnCFVZkqg.png" /></figure><p>Kafka hardens one link in a six-link chain. Its “exactly-once” also only applies <em>inside</em> Kafka (producer → topic → consumer with transactions); end to end, you still need idempotent consumers. <strong>Redis pub/sub is actually weaker than what you have</strong> for this purpose.</p><p>This is the <strong>end-to-end argument</strong>, a classic systems-design principle and great to cite in interviews: <em>reliability must ultimately be checked at the endpoints; making the middle of the pipe more reliable is an optimization, not a guarantee.</em></p><h4>3. How to actually get “never missed, never doubled”</h4><p>Stack these layers. Each one covers a different failure:</p><ol><li><strong>ACID at the source.</strong> Insert the order and its event in <strong>one transaction</strong> (outbox row or NOTIFY). If the order exists, the event exists.</li><li><strong>At-least-once delivery.</strong> Publish, retry on failure. Duplicates are allowed.</li><li><strong>Idempotent client.</strong> The KDS stores tickets keyed by order_id, so the same order arriving twice just overwrites itself: tickets.set(order.id, order) (a Map, not an array push).</li><li><strong>Self-healing view.</strong> A snapshot on every (re)connect, plus a full resync every minute or two. Anything missed in transit appears anyway.</li><li><strong>Application-level acknowledgement.</strong> This is what truly closes the gap. The KDS calls POST /orders/{id}/ack when a ticket is displayed, or when a cook taps it. The backend checks: <em>any order still unacknowledged after 60 seconds?</em> Then it re-alerts, chimes louder, or notifies a manager&#39;s device. This guarantees the cook <strong>saw</strong> it, which no message bus can.</li><li><strong>State machine with conditional updates.</strong> This ensures each order is <em>executed</em> once, even with two tablets or a double tap. Postgres row locking guarantees only one transition wins.</li></ol><pre>UPDATE orders SET status = &#39;preparing&#39;, started_by = :cook<br>WHERE id = :id AND status = &#39;new&#39;;      -- 0 rows updated → someone already started it</pre><p>With this, the guarantee comes from <strong>Postgres + idempotency + ack + reconciliation</strong>, and the pipe (Firestore, SSE, Redis, Kafka) is just the fast path. That’s why a cheap, fire-and-forget pipe is fine for the KDS.</p><h4>4. Where a durable queue does belong</h4><p>The KDS has side effects that can’t be “resynced”: <strong>printing a kitchen ticket</strong>, sending a “your order is ready” SMS, pushing to a delivery partner. Those are category D:</p><ul><li>Outbox → durable queue (Pub/Sub, SQS, Redis Streams)</li><li>Consumer uses an <strong>idempotency key</strong> (print:order-981:v1) so a retry doesn&#39;t print twice</li><li>The printer or provider <strong>acks</strong>; failures retry, then go to a dead-letter queue</li></ul><p>Use the strong pipe only where a duplicate or a miss <strong>can’t be corrected by looking at state again</strong>.</p><h4>5. On “in a perfect world, everything would be SQL ACID”</h4><p>That instinct is half right, and the half that’s right is the important half.</p><ul><li><strong>Right:</strong> business truth (orders, payments, inventory, status transitions) belongs in an ACID store. That’s the anchor of the whole design.</li><li><strong>But ACID stops at the database boundary.</strong> No transaction can span Postgres, a tablet over Wi-Fi, a thermal printer, and Twilio. Once you cross the network to something you don’t control, you’re in a world of at-least-once delivery, retries, idempotency, and reconciliation, whatever tool you use.</li><li><strong>And ACID for everything is wasteful.</strong> Running typing indicators or GPS pings through transactions costs latency, throughput, and money for data nobody needs to keep.</li></ul><p>So the mature version of the rule is:</p><blockquote><strong><em>ACID where the truth lives. At-least-once + idempotency at the edges. Reconciliation as the safety net. Pick the pipe by what it costs you to miss or duplicate a message.</em></strong></blockquote><h3>Cost models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXfK2zTlbB9MTHK6Fl7mBg.png" /></figure><p>Key insight: <strong>idle connections are cheap on machines and expensive on per-request serverless.</strong> That’s why large systems separate a stateless API tier from an always-on <strong>connection/gateway tier</strong>.</p><h4>How companies using SSE optimize cost and scale</h4><p>The industry answer is to <strong>avoid paying per request-second for idle connections</strong> by moving connection-holding onto infrastructure that’s billed differently, and then making each connection as cheap as possible.</p><p><strong>1. Hold connections on always-on machines, not per-request serverless.</strong> An idle SSE connection is very cheap for a machine: a socket plus a few KB of memory, with no CPU while waiting. Async servers (uvicorn/FastAPI, Node, Go) can hold <strong>thousands to tens of thousands</strong> of idle connections on one small machine. LinkedIn, for example, wrote about holding hundreds of thousands of persistent SSE connections on a single machine for its messaging. On a VM, Kubernetes node, or container service billed <strong>per machine-hour</strong>, idle connections cost almost nothing extra; the machine costs the same whether it holds 10 connections or 10,000.</p><p><strong>2. Split the “connection tier” from the API tier.</strong> This is the main architectural pattern:</p><pre>┌──────────────────────┐<br>Customer ──► │  API (stateless)     │──► Postgres<br>POS, Admin   │  scales to zero/out  │<br>             └─────────┬────────────┘<br>                       │ publish &quot;order.created&quot;<br>                       ▼<br>             ┌──────────────────────┐<br>             │  Pub/sub bus         │  (Redis, NATS, Kafka, Pub/Sub, PG NOTIFY)<br>             └─────────┬────────────┘<br>                       ▼<br>             ┌──────────────────────┐<br>KDS screens ◄│  Realtime gateway    │  always-on, holds SSE/WebSocket<br>customers   ◄│  (thin, few machines)│  connections, only forwards events<br>             └──────────────────────┘</pre><ul><li>The <strong>API</strong> does the business logic, stays stateless, and can scale freely, even to zero.</li><li>The <strong>gateway</strong> has one job: hold connections and forward events to the right channel (e.g. restaurant:42:kitchen). It&#39;s simple, rarely deployed, and runs on a few always-on machines.</li><li>The <strong>bus</strong> decouples them, so any API instance can publish and every gateway node receives it, wherever a given KDS is connected.</li></ul><p>Slack’s real-time system, for example, uses separate gateway servers that hold client connections.</p><p><strong>3. Outsource the connection tier.</strong> Many companies skip building the gateway and use <strong>Pusher, Ably, PubNub, or Firebase</strong>. The provider is effectively the gateway, and you pay per message or connection instead of running machines.</p><p><strong>4. Platforms that don’t bill idle connections.</strong> Some edge platforms are designed for this. <strong>Cloudflare Durable Objects</strong> with WebSocket hibernation, for example, can keep a connection open without billing for compute while it’s idle.</p><p><strong>5. Techniques that keep it efficient and scalable</strong> (see the patterns below): snapshot plus resume, graceful draining on deploys, reconnect with jittered backoff, heartbeats, channel-scoped fan-out, long load-balancer timeouts, and per-node connection caps with autoscaling on connection count rather than CPU.</p><p><strong>A sensible progression for a small product:</strong> start with Firestore (or Pusher/Ably) as the connection tier at $0; then keep the API on serverless and add a <strong>tiny always-on realtime gateway</strong> fed by Postgres LISTEN/NOTIFY or Redis, a few dollars a month flat no matter how many screens; at large scale, several gateway nodes behind a load balancer, a proper bus, and autoscaling on connection count. Even 1,000 restaurants × 3–5 screens is roughly 3,000–5,000 mostly idle connections, which one small async server can likely handle.</p><h3>Patterns worth naming</h3><p>Naming these precisely is a strong signal in a design review.</p><ul><li><strong>Snapshot + delta:</strong> send full state on connect, then changes. Makes reconnects safe.</li><li><strong>Sequence numbers / last-event-id:</strong> clients detect gaps and resume.</li><li><strong>Conflation:</strong> for fast-changing values, send only the latest per key (stock tickers, driver location).</li><li><strong>Outbox pattern:</strong> write the event to an outbox table in the same DB transaction; a relay publishes it. Fixes dual writes.</li><li><strong>CDC:</strong> publish events by reading the database’s change log (Debezium, Postgres logical replication).</li><li><strong>Idempotency keys:</strong> consumers record processed IDs so retries are harmless.</li><li><strong>Conditional updates:</strong> UPDATE ... WHERE status = &#39;new&#39; so only one state transition wins.</li><li><strong>Presence via heartbeat + TTL:</strong> clients ping every N seconds; Redis keys with a TTL expire when they stop.</li><li><strong>Gateway tier:</strong> dedicated connection servers subscribed to a backbone; the API stays stateless.</li><li><strong>Dead-letter queue:</strong> messages that keep failing are set aside for inspection instead of blocking.</li></ul><p>For long-lived connections specifically:</p><ul><li><strong>Snapshot plus resume:</strong> on connect, send current state; tag events with id: so the client can resume with Last-Event-ID. Dropped connections then lose nothing.</li><li><strong>Graceful draining on deploys:</strong> when a gateway node restarts, close connections gradually so thousands of clients don’t reconnect at once.</li><li><strong>Reconnect with jittered backoff:</strong> clients wait a random 1–5 seconds before reconnecting, which avoids a thundering herd after an outage.</li><li><strong>Heartbeats</strong> every 15–30 seconds, so load balancers and proxies don’t silently kill idle connections, and dead clients are detected.</li><li><strong>Channel-scoped fan-out:</strong> each node subscribes only to the channels its connected clients need, rather than every event.</li><li><strong>Long load-balancer timeouts:</strong> configure LBs for long-lived connections; defaults often cut at 30–60 seconds.</li><li><strong>Per-node connection caps plus autoscaling on connection count</strong>, rather than on CPU, since CPU stays low.</li></ul><h3>Classic interview cases, mapped</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btM1CuUKUsTfhsTK8QZUTQ.png" /></figure><h4>Deep dive: a KDS with Firestore or SSE</h4><p>The two apps never talk to each other directly. <strong>The backend is the hub</strong>: the customer app sends the order to the backend, and the backend pushes it out to the KDS. The same channel carries status updates back to the customer (“Preparing” → “Ready”).</p><pre>Customer app ──POST /orders──► API ──► Postgres (source of truth)<br>                               │<br>                               └──push event──► KDS (new ticket)<br>KDS ──PATCH /orders/{id}/status──► API ──push event──► Customer (order status)</pre><p>The open question is what does the “push.” The realistic options:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CR0ei4P9pHRPb5drwXfKoA.png" /></figure><p><strong>Firestore: upsides</strong></p><ul><li><strong>Free at small scale.</strong> A busy restaurant doing about 300 orders/day with about 4 status changes each is roughly 1,200 writes and a few thousand reads per day, well under the free quota.</li><li><strong>No open connections on your server.</strong> Serverless backends still scale to zero between orders.</li><li><strong>Reconnects, offline cache, and fan-out are handled for you.</strong> A KDS tablet that drops Wi-Fi resyncs automatically.</li><li><strong>Customer status updates come free</strong> with the same mechanism.</li><li><strong>Little backend code</strong>: one publish_order() function.</li></ul><p><strong>Firestore: downsides</strong></p><ul><li><strong>Dual write</strong>: Postgres and Firestore can disagree, and a failed second write means a missing ticket. You need retries or an outbox, plus a periodic REST resync.</li><li><strong>Second schema</strong> to keep in step with Postgres. Keep the Firestore doc small and display-only.</li><li><strong>Firebase Auth required for listeners</strong>: anonymous auth for guests, custom claims for staff, and security rules to get right and test with the emulator.</li><li><strong>Vendor lock-in</strong> in both frontends.</li><li><strong>Per-read billing</strong> can surprise you: each change counts as a read for each listening screen, and a listener bug that re-subscribes in a loop burns quota fast. Set a budget alert.</li><li><strong>Cleanup</strong>: served orders pile up; set a TTL policy.</li></ul><p><strong>SSE: upsides</strong></p><ul><li><strong>Single source of truth.</strong> NOTIFY fires inside the same Postgres transaction as the order insert, so if the order exists, the event was sent. No dual write.</li><li><strong>No new vendor or auth system.</strong> It uses your existing JWT/session auth and REST API.</li><li><strong>Portable.</strong> It works on Cloud Run, a VM, AWS, anywhere.</li><li><strong>Full control</strong> over event shape, per-station filtering, and logging. It’s easier to debug because it’s just your code.</li><li><strong>Simple client</strong>: EventSource is built into browsers and reconnects automatically.</li></ul><p><strong>SSE: downsides</strong></p><ul><li><strong>Cost on per-request serverless</strong> (see Cost models): an open stream keeps an instance billed.</li><li><strong>Request timeout.</strong> Cloud Run caps requests at 60 minutes, so streams get cut; the snapshot-on-connect pattern covers any gap.</li><li><strong>Fan-out is your job.</strong> With more than one instance, you need LISTEN/NOTIFY or Redis.</li><li><strong>Auth quirk</strong> and <strong>routing</strong>: EventSource can&#39;t send an Authorization header, and the stream should go directly to the backend domain, not through a static-hosting rewrite.</li><li><strong>More to operate.</strong> Missed-event recovery, connection limits, and monitoring are on you.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g02aNkVgIDZoYxwtxsGzdw.png" /></figure><p><strong>Recommendation.</strong> At MVP stage with a $0 target, Firestore (or Pusher/Ably) wins on cost; with a REST resync on load and every few minutes, the dual-write risk is manageable. Once restaurants are paying, SSE becomes attractive, especially on an always-on VM where idle connections cost nothing extra. Whichever you start with, keep the frontend behind one subscribeToActiveOrders(restaurantId, onChange) function and have the backend emit the same event shape (order.created, order.status_changed), so switching later only touches that function and one publisher.</p><h3>How to say it in an interview</h3><p>The rule of thumb: <strong>ACID where the truth lives. At-least-once + idempotency at the edges. Reconciliation as the safety net. Pick the pipe by what it costs you to miss or duplicate a message, and pick the platform by how its billing treats idle connections.</strong></p><p>A short version, covering categories, transport, backbone and architecture:</p><blockquote><em>“Before picking tech, I’d classify the real-time data. The KDS needs </em><strong><em>state sync</em></strong><em>: the current open tickets matter, not every intermediate update, so I’ll use snapshot-plus-delta, and a dropped event just triggers a resync. Ticket </em><strong><em>printing</em></strong><em> is different: it’s a side effect that must happen once, so it goes through a durable queue with idempotent consumers. For transport, it’s server-to-client, so SSE is enough. For fan-out across API instances I’d use Redis pub/sub, and I’d hold connections on a dedicated gateway tier so the API can stay stateless and autoscale.”</em></blockquote><p>That one paragraph covers categories, delivery guarantees, transport choice, backbone, and cost-aware architecture, which are the five things interviewers probe.</p><p>A longer version, when they push on reliability:</p><blockquote><em>“The order itself is the critical thing, so it’s committed in Postgres along with an outbox event in the same transaction. Delivery to the KDS is at-least-once and the client dedupes by order ID, so duplicates are harmless; on reconnect it pulls a snapshot, so gaps heal. To guarantee a cook actually </em>saw<em> the order, the KDS acks each ticket and we alert on unacknowledged orders after 60 seconds. Status changes use conditional updates so two cooks can’t start the same order. Ticket printing is a real side effect, so that goes through a durable queue with idempotency keys. I wouldn’t put Kafka in the KDS path: it hardens the middle of the pipe, but the risky hops are the database-to-publish step and the last mile to the tablet, which it doesn’t cover.”</em></blockquote><p>Three habits make these answers land: classify before naming tools, say where each guarantee lives, and mention the cost model when connections are long-lived.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01db1cf7833a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Bundling in Web Development]]></title>
            <link>https://blog.stackademic.com/understanding-bundling-in-web-development-d19bf53ec4f9?source=rss-29613658adba------2</link>
            <guid isPermaLink="false">https://medium.com/p/d19bf53ec4f9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[bundling]]></category>
            <category><![CDATA[vitejs]]></category>
            <dc:creator><![CDATA[Sushmitha Dhummi Thrilochana]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 01:30:36 GMT</pubDate>
            <atom:updated>2025-01-05T12:29:32.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A-xzs8PSzfNJaLI0" /><figcaption>Photo by <a href="https://unsplash.com/@adidhotre?utm_source=medium&amp;utm_medium=referral">Aditya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bundling is a vital step in modern web development, especially for building efficient and optimized web applications. In this article, we’ll explore the concept of bundling, its benefits, what happens when an application isn’t bundled, and provide a step-by-step example of using Vite to bundle a React app.</p><h3>What is Bundling?</h3><blockquote>Bundling is the process of combining multiple files — such as JavaScript, CSS, and images — into fewer or single files.</blockquote><p>This optimization step reduces the number of requests made to the server, improves performance, and ensures faster load times for web applications.</p><h3>Why is Bundling Needed?</h3><p>Bundling has become a best practice in production environments due to its many benefits:</p><ol><li><strong>Reduced HTTP Requests</strong>: Browsers limit the number of simultaneous requests per domain. Bundling reduces the total number of requests, significantly improving load times.</li><li><strong>Minification and Optimization</strong>: Bundlers compress files by removing unnecessary whitespace, comments, and formatting, reducing the overall file size.</li><li><strong>Tree-Shaking</strong>: Modern bundlers like Vite and Webpack remove unused code, ensuring that only the necessary parts are sent to the browser.</li><li><strong>Cache Efficiency</strong>: Bundled files often include hashed names (e.g., main.123abc.js), making it easier for browsers to cache them effectively.</li><li><strong>Enhanced Security</strong>: By obfuscating and minifying the code, bundling can make it harder for attackers to reverse-engineer the application.</li></ol><h3>What Happens if Application is Not Bundled?</h3><p>Without bundling, the application will simply have <strong>longer load time</strong>. Because —</p><ul><li><strong>More HTTP Requests</strong>: The browser must fetch each file individually, leading to slower load times.</li><li><strong>Larger File Sizes</strong>: Without minification, file sizes remain large, impacting download speeds.</li><li><strong>Unoptimized Code</strong>: Tree-shaking and code-splitting are not applied, resulting in unused code being sent to the browser.</li></ul><h3>Simple Analogy</h3><p>Imagine ordering groceries online,</p><p><strong>Without Bundling</strong>: Each item is delivered in its own package. You waste time and effort managing multiple deliveries.</p><p><strong>With Bundling</strong>: All your groceries are packed into one or two boxes, saving delivery time and effort.</p><h3>React Example: Bundling with Vite</h3><p>Let’s see how a React app structure changes when using Vite for development and bundling.</p><h4>1. Initial React App Structure</h4><p>Create a simple React app using Vite (npm create vite@latest)</p><pre>my-vite-react-app/<br>├── public/                  # Static assets<br>├── src/                     # Source files<br>│   ├── App.jsx              # Main React component<br>│   ├── main.jsx             # Entry point<br>│   ├── components/          # React components<br>│   │   └── Button.jsx<br>│   └── styles.css           # CSS file<br>├── index.html               # Main HTML file<br>├── package.json             # Project dependencies<br>├── vite.config.js           # Vite configuration</pre><h4>2. Development with Vite <strong>(Unbundled Development)</strong></h4><p>In development mode, <strong>Vite</strong> doesn’t bundle the application; instead, it serves the app via an ES module-based development server. The src/main.jsx file and its imports are loaded dynamically as individual ES modules.</p><p>Open the <strong>Network Tab</strong> in Google DevTools:</p><ul><li>You’ll see individual requests for each file — main.jsx, App.jsx, Button.jsx, and styles.css from your localhost server.</li></ul><h4>3. After Vite Bundling (Production Build)</h4><p>Run the following command to build the app for production:</p><pre>npm run build</pre><ul><li>Vite bundles the application into a highly optimized format.</li><li>The output is placed in the dist/ directory. (The bundled output files have hashed names for cache busting)</li></ul><p>Directory structure after bundling:</p><pre>dist/<br>├── assets/                  # Bundled assets<br>│   ├── index.abcd1234.js    # Main bundled JavaScript (hashed)<br>│   ├── index.efgh5678.css   # CSS bundle (hashed)<br>│   ├── vendor.abcd1234.js   # Third-party libraries<br>│   └── logo.1234abcd.svg    # Optimized static assets<br>├── index.html               # Production HTML file</pre><h4>What Changes in Bundled Files?</h4><p>If you open each of bundled file under dist/ you will notice some of below changes</p><ol><li><strong>JavaScript Bundles</strong>:<br>- If you open the index.abcd1234.js you will see that the Code is minified and obfuscated.<br>- Vendor libraries (e.g., React) are split into a separate file (vendor.abcd1234.js) for caching.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ydkN3ZY0mtHQQgcAgM1ksA.png" /></figure><p><strong>2. CSS Files</strong>:<br>- Combined and minified into a single file (index.efgh5678.css).</p><p><strong>3 .</strong><strong>index.html</strong>: <br>- The &lt;script&gt; tags under &lt;head&gt; are replaced with a single script pointing to the bundled JavaScript and CSS files.</p><pre>&lt;script type=&quot;module&quot; src=&quot;/assets/index.abcd1234.js&quot;&gt;&lt;/script&gt;<br>&lt;link rel=&quot;stylesheet&quot; crossorigin href=&quot;/assets/index.efgh5678.css&quot;&gt;</pre><p><strong>In Google DevTools , Network Tab</strong>:</p><p>You will notice fewer HTTP requests —</p><ul><li>A single request for the main JavaScript file (e.g., index.abcd1234.js).</li><li>Requests for vendor JS, CSS, and static assets (e.g., logo.1234abcd.svg).</li><li>Files have hashed names for cache busting.</li></ul><h3>Lastly…</h3><p>Bundling is a general concept applicable across various software development domains, not just web development. Tools like Webpack, Vite, and Parcel help automate and optimize the bundling process, making it an essential step for production-ready applications.</p><p>By bundling, developers ensure their web applications are performant, efficient, and ready for deployment in real-world environments. Their specifics depend on the platform, language, or ecosystem they target.</p><p>Here’s an overview various bundler tools:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*QPz5_57b4lNe5XRlvg7Egg.png" /></figure><p><strong>Thank you for reading!</strong> If you found this article helpful, consider leaving a clap 👏 or sharing it with others.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d19bf53ec4f9" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/understanding-bundling-in-web-development-d19bf53ec4f9">Understanding Bundling in Web Development</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Reusable Tooltip Component in React: Step-by-Step Guide]]></title>
            <link>https://blog.stackademic.com/how-to-build-a-reusable-tooltip-component-in-react-step-by-step-guide-c7e18ae63642?source=rss-29613658adba------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7e18ae63642</guid>
            <category><![CDATA[tooltips]]></category>
            <category><![CDATA[demo]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[reusable-component]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sushmitha Dhummi Thrilochana]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 03:46:07 GMT</pubDate>
            <atom:updated>2024-11-18T13:31:04.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*e-tAP-CSa1WLOHWOeHdQAQ.png" /></figure><p>Building a reusable tooltip component is an excellent way to enhance your React skills. This project will walk you through creating a customizable and maintainable tooltip in a step-by-step approach with a code sandbox demo at the end of each section.</p><p>Here’s an overview of the upcoming sections:</p><p><strong>Part 1:</strong> <a href="#7b7e">Creating the Basic Tooltip Component</a><br><strong>Part 2</strong>: <a href="#6b3b">Adding Custom Placement Options</a><br><strong>Part 3:</strong> <a href="#ca6e">Adding Advanced Features to the Tooltip</a><br><strong>Part 4: </strong><a href="#ad92">Theming and Advanced Customization</a></p><p><em>You can find the full component sandbox demo at the end of the article!</em></p><h4>🤔 Using CSS Hover or React state?</h4><p>While you could implement simple hover-based tooltips using CSS, using React’s useState offers more flexibility, such as advanced behavior control, delay, conditional rendering, and interactive elements.</p><p>In this article, we’ll progressively build a reusable tooltip component from a basic to an advanced version with various customization.</p><h3>Part 1: Creating the Basic Tooltip Component</h3><p>Let’s start by building a basic version of tooltip component using React. We’ll use React’s useState hook to create a state variable for managing tooltip visibility when the user hovers over an element.</p><p><strong>Basic Tooltip Component Code</strong>:</p><pre>// Tooltip.js<br>import React, { useState } from &quot;react&quot;;<br>import &quot;./Tooltip.css&quot;;<br><br>const Tooltip = ({ children, message = &quot;Tooltip!&quot; }) =&gt; {<br>  const [isVisible, setIsVisible] = useState(false);<br><br>  const showTooltip = () =&gt; setIsVisible(true);<br>  const hideTooltip = () =&gt; setIsVisible(false);<br><br>  return (<br>    &lt;&gt;<br>      &lt;div<br>        className=&quot;tooltip-container&quot;<br>        onMouseEnter={showTooltip}<br>        onMouseLeave={hideTooltip}<br>      &gt;<br>        {children}<br>        {isVisible &amp;&amp; (<br>          &lt;div className=&quot;tooltip&quot;&gt;<br>            &lt;div&gt;{message}&lt;/div&gt;<br>          &lt;/div&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Tooltip;</pre><p><strong>Explanation</strong>:</p><ul><li>isVisible state is used to conditionally render tooltip.</li><li>The onMouseEnter and onMouseLeave events are used to update isVisible to show and hide the tooltip.</li></ul><h4><strong>Basic CSS Code</strong>:</h4><p>Without CSS, the tooltip element comes below the message and spans out. This basic CSS sets up the tooltip to appear directly above the message.</p><pre>/* Tooltip.css */<br>.tooltip-container {<br>  position: relative; /* Position reference for elements inside*/<br>  display: inline-block; /* Fits around content */<br>}<br><br>.tooltip {<br>  position: absolute; /* Positions tooltip relative to container */<br>  bottom: 100%; /* Places tooltip above container */<br>  left: 50%; /* Centers tooltip */<br>  transform: translateX(-50%); /* Perfect centering */<br>  background-color: black;<br>  color: white;<br>  padding: 14px;<br>  border-radius: 6px;<br>  opacity: 0.85;<br>  margin-bottom: 8px;<br>  z-index: 1; /* On top */<br>}</pre><p>Key CSS properties to note:</p><ul><li><strong>.tooltip-container</strong> should have position: relative to create a local reference for the tooltip&#39;s placement . The display: inline-block ensures the container wraps around inline content properly preventing it from stretching across the entire width of a parent block</li><li><strong>.tooltip</strong> uses position: absolute to position itself relative to .tooltip-container.</li><li><strong>bottom: 100%</strong> places the tooltip directly above the container.</li></ul><p><strong>Try it out! </strong>Tooltip part-1 <a href="https://codesandbox.io/p/sandbox/9qzsxq?file=%2Fsrc%2FApp.js%3A13%2C1">sandbox here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F9qzsxq%3Ffile%3D%252Fsrc%252FApp.js%253A13%252C1&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fp%2Fsandbox%2F9qzsxq%3Ffile%3D%252Fsrc%252FApp.js%253A13%252C1&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F9qzsxq%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4f02ffb3ee3dfc5c6c6e989ee0e5d46/href">https://medium.com/media/a4f02ffb3ee3dfc5c6c6e989ee0e5d46/href</a></iframe><h3>Part 2: Adding Custom Placement Options</h3><p>Now, we’ll extend the component to support different tooltip placements (top, bottom, left, right) based on the prop received along with arrow.</p><h4><strong>Code Update</strong>:</h4><pre>import React, { useState } from &quot;react&quot;;<br>import &quot;./Tooltip.css&quot;;<br><br>const VALID_PLACEMENTS = [&quot;top&quot;, &quot;bottom&quot;, &quot;left&quot;, &quot;right&quot;];<br><br>const Tooltip = ({ children, message = &quot;Tooltip!&quot;, placement = &quot;top&quot; }) =&gt; {<br>  const [isVisible, setIsVisible] = useState(false);<br>  <br>  placement = VALID_PLACEMENTS.includes(placement) ? placement : &quot;top&quot;;<br><br>  const showTooltip = () =&gt; setIsVisible(true);<br>  const hideTooltip = () =&gt; setIsVisible(false);<br><br>  return (<br>    &lt;div<br>      className=&quot;tooltip-container&quot;<br>      onMouseEnter={showTooltip}<br>      onMouseLeave={hideTooltip}<br>    &gt;<br>      {children}<br>      {isVisible &amp;&amp; (<br>        &lt;div className={`tooltip tooltip-${placement}`}&gt;<br>          &lt;div&gt;{message}&lt;/div&gt;<br>          &lt;div className={`tooltip-arrow tooltip-arrow-${placement}`} /&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Tooltip;</pre><ul><li>We added a placement prop that determines where tooltip appears relative to its trigger element and applies relevant CSS class for placement and arrow.</li><li>We added a arrow element with CSS styling as below.</li></ul><h4><strong>CSS Update: Styling for Placement and Arrow</strong>:</h4><pre>.tooltip-container {<br>  position: relative;<br>  display: inline-block;<br>}<br>.tooltip {<br>  position: absolute;<br>  background-color: black;<br>  color: white;<br>  padding: 14px;<br>  opacity: 0.85;<br>  border-radius: 6px;<br>  z-index: 1;<br>}<br><br>/* Placement Styles */<br>.tooltip-top {<br>  bottom: 100%;<br>  left: 50%;<br>  transform: translateX(-50%);<br>  margin-bottom: 14px;<br>}<br>.tooltip-bottom {<br>  top: 100%;<br>  left: 50%;<br>  transform: translateX(-50%);<br>  margin-top: 14px;<br>}<br>.tooltip-left {<br>  right: 100%;<br>  top: 50%;<br>  transform: translateY(-50%);<br>  margin-right: 14px;<br>}<br>.tooltip-right {<br>  left: 100%;<br>  top: 50%;<br>  transform: translateY(-50%);<br>  margin-left: 14px;<br>}<br><br>/* Arrow Styles */<br>.tooltip-arrow {<br>  position: absolute;<br>  width: 0;<br>  height: 0;<br>  border-style: solid;<br>}<br>.tooltip-arrow-top {<br>  top: 100%;<br>  left: 50%;<br>  transform: translateX(-50%);<br>  border-width: 8px 8px 0 8px;<br>  border-color: black transparent transparent transparent;<br>}<br>.tooltip-arrow-bottom {<br>  bottom: 100%;<br>  left: 50%;<br>  transform: translateX(-50%);<br>  border-width: 0 8px 8px 8px;<br>  border-color: transparent transparent black transparent;<br>}<br>.tooltip-arrow-left {<br>  left: 100%;<br>  top: 50%;<br>  transform: translateY(-50%);<br>  border-width: 8px 0px 8px 8px;<br>  border-color: transparent transparent transparent black;<br>}<br>.tooltip-arrow-right {<br>  right: 100%;<br>  top: 50%;<br>  transform: translateY(-50%);<br>  border-width: 8px 8px 8px 0px;<br>  border-color: transparent black transparent transparent;<br>}</pre><p><strong>Try it out: </strong>Part-2 <a href="https://codesandbox.io/p/sandbox/85h2q8?file=%2Fsrc%2FApp.js%3A13%2C1">code sandbox</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F85h2q8%3Ffile%3D%252Fsrc%252FApp.js%253A13%252C1&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fp%2Fsandbox%2F85h2q8%3Ffile%3D%252Fsrc%252FApp.js%253A13%252C1&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F85h2q8%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a9d0ec2af8fff7597c1b3e85aeee90c/href">https://medium.com/media/8a9d0ec2af8fff7597c1b3e85aeee90c/href</a></iframe><h3>Part 3: Adding Advanced Features to the Tooltip</h3><p>In this part, we will enhance our basic tooltip component by adding more customizable and interactive features, to make the it more versatile, allowing developers to customize it for various use cases in their applications.</p><p>We will incorporate following features</p><ol><li><strong>Delay: </strong>Allow user to specify a delay for the tooltip to show or hide.<br><em>- Approach: </em>Use setTimeout in showTooltip() and hideTooltip() to update isVisible state with delay received from delay prop object.</li><li><strong>Sticky Behavior: </strong>Keeps the tooltip visible until it is manually closed.</li><li><strong>Title: </strong>Display a title in the tooltip.</li><li><strong>Icon</strong>: For displaying an icon in the tooltip, to make it more informative.</li><li><strong>Close Button</strong>: To manually dismiss the tooltip. Must appear by default for tooltips with sticky behavior.</li><li><strong>Initial Visibility: </strong>Initial state of tooltip when the component first loads.</li><li><strong>Max Width: </strong>Allow customization of the tooltip’s maximum width.</li></ol><p>We will be adding following props — title, icon, dismissible, sticky, delay, initialVisible, and maxWidth. Since these features are optional, we will be conditionally rendering them and provide default values in the component.</p><p><strong>Updated Component:</strong></p><pre>import React, { useState } from &quot;react&quot;;<br>import &quot;./Tooltip.css&quot;;<br>import { IoClose } from &quot;react-icons/io5&quot;;<br><br>const VALID_PLACEMENTS = [&quot;top&quot;, &quot;bottom&quot;, &quot;left&quot;, &quot;right&quot;];<br><br>const Tooltip = ({<br>  children,<br>  icon,<br>  title,<br>  message = &quot;Tooltip!&quot;,<br>  placement = &quot;top&quot;,<br>  initialVisible = &quot;false&quot;,<br>  delay = { show: 300, hide: 300 },<br>  dismissible = false,<br>  sticky = false,<br>  arrow = false,<br>  maxWidth = &quot;300px&quot;,<br>}) =&gt; {<br>  placement = VALID_PLACEMENTS.includes(placement) ? placement : &quot;top&quot;;<br><br>  const [isVisible, setIsVisible] = useState(initialVisible);<br><br>  // Adding delay<br>  const showTooltip = () =&gt; {<br>    setTimeout(() =&gt; setIsVisible(true), delay.show);<br>  };<br>  const hideTooltip = () =&gt; {<br>    setTimeout(() =&gt; setIsVisible(sticky), delay.hide);<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;div<br>        className=&quot;tooltip-container&quot;<br>        onMouseEnter={showTooltip}<br>        onMouseLeave={hideTooltip}<br>      &gt;<br>        {children}<br>        {isVisible &amp;&amp; (<br>          &lt;div<br>            className={`tooltip tooltip-${placement}`}<br>            style={{ maxWidth: maxWidth }}<br>          &gt;<br>            {icon &amp;&amp; &lt;span className=&quot;tooltip__icon&quot;&gt;{icon}&lt;/span&gt;}<br>            &lt;div className=&quot;tooltip__content&quot;&gt;<br>              {title &amp;&amp; &lt;span className=&quot;tooltip__title&quot;&gt;{title}&lt;/span&gt;}<br>              &lt;span className=&quot;tooltip__message&quot;&gt;{message}&lt;/span&gt;<br>            &lt;/div&gt;<br>            <br>            {(dismissible || sticky) &amp;&amp; (<br>              &lt;IoClose<br>                onClick={() =&gt; setIsVisible(false)}<br>                className=&quot;tooltip__close&quot;<br>              /&gt;<br>            )}<br><br>            {arrow &amp;&amp; (<br>              &lt;div className={`tooltip-arrow tooltip-arrow-${placement}`} /&gt;<br>            )}<br>          &lt;/div&gt;<br>        )}<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default Tooltip;</pre><p>Additional CSS classes added in Tooltip.js</p><pre>.tooltip__icon {<br>  color: #c7c7c7;<br>  font-size: 18px;<br>  width: 24px;<br>  height: 24px;<br>  /* flex-shrink: 0; */<br>  display: flex;<br>  justify-content: center;<br>  align-items: center;<br>}<br><br>.tooltip__content {<br>  display: flex;<br>  flex-direction: column;<br>  gap: 1px;<br>}<br>.tooltip__title {<br>  color: #fff;<br>  font-size: 14px;<br>  font-style: normal;<br>  font-weight: 500;<br>  line-height: 20px;<br>}<br>.tooltip__message {<br>  color: #c7c7c7;<br>  font-size: 14px;<br>  font-style: normal;<br>  font-weight: 400;<br>  line-height: 20px;<br>}<br><br>/* Tooltip close button */<br>.tooltip__close {<br>  cursor: pointer;<br>  color: #c7c7c7;<br>  font-size: 20px;<br>  flex-shrink: 0;<br>}<br>.tooltip__close:hover {<br>  color: #fff;<br>}</pre><p><strong>Try it out!</strong> Part-3 <a href="https://codesandbox.io/p/sandbox/tooltip-part-3-65t58t?file=%2Fsrc%2FApp.js">sandbox</a>. (<em>Try to add more features of your own!</em> )</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ftooltip-part-3-65t58t&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fp%2Fsandbox%2Ftooltip-part-3-65t58t&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F65t58t%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed2d2681008bc3ae46bad5f3782052bc/href">https://medium.com/media/ed2d2681008bc3ae46bad5f3782052bc/href</a></iframe><h3>Part 4: Theming and Advanced Customization</h3><p>In earlier versions of the tooltip component, colors were hardcoded directly into the CSS. In this part, we’ll explore how to add theming to your tooltip component using CSS variables. This method provides a flexible and maintainable way to switch themes dynamically.</p><p>To implement theming, we need to make two changes to our CSS —</p><ol><li><strong>Defining Theme Variables:</strong> Create CSS variables for each theme to store color values in each theme class. These variables ensure each theme has its own consistent style. These can be defined in the same CSS file or separate theme files.</li></ol><p><strong>Example:</strong></p><pre>/* Dark Theme */<br>.tooltip-theme-dark {<br>  --tooltip-bg: #333;<br>  --tooltip-title-color: #fff;<br>  --tooltip-message-color: #c7c7c7;<br>  --tooltip-icon-color: #c7c7c7;<br>  --tooltip-close-color: #c7c7c7;<br>  --tooltip-close-hover-color: #fff;<br>}<br><br>/* Light Theme */<br>.tooltip-theme-light {<br>  --tooltip-bg: #f9f9f9;<br>  --tooltip-title-color: #111827;<br>  --tooltip-message-color: #6b7280;<br>  --tooltip-icon-color: #6b7280;<br>  --tooltip-close-color: #6b7280;<br>  --tooltip-close-hover-color: #111827;<br>}</pre><p>2. <strong>Replace Hardcoded Colors with CSS Variables: </strong>Replace the hardcoded color values in your CSS with the corresponding CSS variables.</p><pre>.tooltip {<br>  background-color: var(--tooltip-bg);<br>  color: var(--tooltip-message-color);<br>  /* Rest of the CSS styling */<br>}<br><br>.tooltip__title {<br>  color: var(--tooltip-title-color);<br>  /* Rest of the CSS styling */<br>}<br><br>.tooltip__icon {<br>  color: var(--tooltip-icon-color);<br>  /* Rest of the CSS styling */<br>}<br><br>.tooltip__close {<br>  color: var(--tooltip-close-color);<br>  /* Rest of the CSS styling */<br>}<br><br>.tooltip__close:hover {<br>  color: var(--tooltip-close-hover-color);<br>  /* Rest of the CSS styling */<br>}</pre><p><strong>Finally,</strong> To make use of these themes, the Tooltip component is updated to accept a theme prop:</p><pre>/* Tooltip.js */<br>const VALID_THEMES = [&quot;dark&quot;, &quot;light&quot;, &quot;blue&quot;, &quot;green&quot;, &quot;pink&quot;];<br><br>const Tooltip = ({ theme = &quot;dark&quot;, ...props }) =&gt; {<br>  // Validate the theme prop<br>  theme = VALID_THEMES.includes(theme) ? theme : &quot;dark&quot;;<br><br>  return (<br>    &lt;div className={`tooltip-container tooltip-theme-${theme}`}&gt;<br>      {/* Previous Tooltip content */}<br>    &lt;/div&gt;<br>  );<br>};</pre><p><strong>Try it out! </strong>Part-4 CodeSandbox demo (Switch themes to see the changes)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ftooltip-part-4-s5gf52%3Ffile%3D%252Fsrc%252Fcomponents%252FTooltip.css%253A145%252C25&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fp%2Fsandbox%2Ftooltip-part-4-s5gf52%3Ffile%3D%252Fsrc%252Fcomponents%252FTooltip.css%253A145%252C25&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fs5gf52%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ab357e3872b4dde6f5a72e5bb864c92/href">https://medium.com/media/0ab357e3872b4dde6f5a72e5bb864c92/href</a></iframe><h3>Conclusion</h3><p>By following these incremental steps, you can develop a robust and customizable React tooltip component. Experiment with additional features such as animations and interactive content for further learning.</p><p>Thank you for taking the time to read this guide, I hope you found it insightful and helpful for your projects. If you enjoyed this article or learned something new, please consider leaving a comment or giving it a clap. Your feedback is much appreciated and encourages me to keep sharing more content like this! 😀</p><p><em>(Tooltip design inspired by this </em><a href="https://www.figma.com/design/8z3MzQUTw2STq71aHbjYaF/Component-Library?node-id=406-401&amp;node-type=canvas&amp;t=tLYVo2F1SflzbW8T-0"><em>Figma file</em></a><em> from the Scrimba React course)</em></p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7e18ae63642" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-build-a-reusable-tooltip-component-in-react-step-by-step-guide-c7e18ae63642">How to Build a Reusable Tooltip Component in React: Step-by-Step Guide</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Material UI Customization in React: Best Practices and Choosing the Right Approach]]></title>
            <link>https://blog.stackademic.com/mastering-material-ui-customization-in-react-best-practices-and-choosing-the-right-approach-9fdfb81a74c2?source=rss-29613658adba------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fdfb81a74c2</guid>
            <category><![CDATA[ui-ux]]></category>
            <category><![CDATA[mui]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[material-ui]]></category>
            <category><![CDATA[customization]]></category>
            <dc:creator><![CDATA[Sushmitha Dhummi Thrilochana]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 07:10:08 GMT</pubDate>
            <atom:updated>2024-11-06T05:35:47.458Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*SsOEjMEiQr_AcR0QGzOyXA.png" /></figure><p>Material UI (MUI) offers a variety of ways to customize components in React.js, allowing you to achieve consistent design across your application.</p><p>Here are some of the key methods:</p><ol><li>sx <a href="#08f2">Prop</a></li><li><a href="#ff0a">Using MUI’s </a>styled() <a href="#ff0a">API</a></li><li><a href="#e700">Theme Customization by using</a> createTheme</li><li><a href="#77c7">Overriding MUI Default Styles with CSS</a></li><li><a href="#8d79">Component-Specific API Customization</a></li><li><a href="#8bf0">Using Emotion (for MUI v5+)</a></li></ol><h3><strong>1. SX Prop</strong></h3><p>The sx prop is a shorthand for applying custom styles directly on a component. It’s a powerful way to adjust component styles inline, using MUI&#39;s theme variables.</p><h4><strong>Best for:</strong></h4><ul><li>Quick, inline customizations on components.</li><li>Adding one-off adjustments, such as padding, margin, color, etc.</li></ul><pre>&lt;Button sx={{ backgroundColor: &#39;primary.main&#39;, padding: &#39;8px 16px&#39; }}&gt;<br>  Customized Button<br>&lt;/Button&gt;</pre><h4><strong>Pros:</strong></h4><ul><li>Compact and very readable for minor adjustments.</li><li>Highly flexible with easy access to theme variables.</li></ul><h4><strong>Cons:</strong></h4><ul><li>Can lead to inconsistent styling if overused without guidelines.</li></ul><h4><strong>When Not to Use:</strong></h4><ul><li>Avoid using sx for large-scale or complex styling that’s better organized in styled() or custom components.</li><li>Avoid overusing it for reusable components, as it can make it hard to maintain styles across different uses.</li></ul><h3><strong>2. Using MUI’s </strong><strong>styled() API</strong></h3><p>MUI’s styled() function provides a way to create custom-styled components while preserving theme consistency.</p><h4><strong>Best for:</strong></h4><ul><li>Creating fully customized components that need to inherit theme settings.</li><li>Reusable components where the styles are tightly coupled with the component.</li></ul><pre>import { styled } from &#39;@mui/material/styles&#39;;<br>import Button from &#39;@mui/material/Button&#39;;<br><br>const CustomButton = styled(Button)(({ theme }) =&gt; ({<br>  backgroundColor: theme.palette.primary.main,<br>  color: &#39;#fff&#39;,<br>  &#39;&amp;:hover&#39;: {<br>    backgroundColor: theme.palette.primary.dark,<br>  },<br>}));</pre><h4><strong>Pros:</strong></h4><ul><li>Maintains theme consistency.</li><li>Allows for scoped styles, reducing CSS conflicts.</li></ul><h4><strong>Cons:</strong></h4><ul><li>May lead to code bloat if used excessively for minor styles.</li></ul><h4><strong>When Not to Use:</strong></h4><ul><li>Avoid for simple, one-off styles that don’t need reusability or theme inheritance, as sx or inline styles might be more efficient.</li></ul><h3>3. Theme Customization</h3><p>You can globally customize the MUI theme by using createTheme and setting up a custom theme provider. This allows to override MUI’s default styling for a consistent look across all components.</p><h4><strong>Best for:</strong></h4><ul><li>Global styles that apply consistently across the application, such as colors, typography, or primary component styles.</li><li>Establishing an app-wide theme with colors, typography, and spacing that <strong>all MUI components</strong> adhere to.</li></ul><pre>import { createTheme, ThemeProvider } from &#39;@mui/material/styles&#39;;<br><br>const theme = createTheme({<br>  palette: {<br>    primary: {<br>      main: &#39;#ff5722&#39;,<br>    },<br>  },<br>  typography: {<br>    fontFamily: &#39;Roboto, Arial&#39;,<br>  },<br>});<br><br>// Wrap your app with ThemeProvider<br>&lt;ThemeProvider theme={theme}&gt;<br>  &lt;App /&gt;<br>&lt;/ThemeProvider&gt;</pre><h4><strong>Pros:</strong></h4><ul><li>Ensures consistency across the app.</li><li>Simplifies future style changes by centralizing them in one place.</li></ul><h4><strong>Cons:</strong></h4><ul><li>Changes apply globally, which may affect components unexpectedly if not thoroughly tested.</li></ul><h4><strong>When Not to Use:</strong></h4><ul><li>Avoid for small, localized styling needs or temporary customizations, as this can lead to bloated theme configurations.</li><li>Not recommended for fine-tuning individual components — use component-specific overrides instead.</li></ul><h3>4. <strong>Overriding MUI Default Styles with CSS</strong></h3><ul><li>You can use the className prop to apply custom CSS classes to components, allowing you to selectively override default MUI styles.</li></ul><pre>&lt;Button className=&quot;my-custom-button&quot;&gt;Styled with CSS&lt;/Button&gt;</pre><pre>/* CSS file */<br>.my-custom-button {<br>  background-color: #00796b;<br>  color: white;<br>}</pre><ul><li>Alternatively, global CSS styles can be used, but this approach may affect all instances of a component, so be cautious with scoping.<br>For example, if you apply a CSS rule like this:</li></ul><pre>.MuiButton-root {<br>  background-color: #00796b;<br>  color: white;<br>}</pre><h4><strong>Pros:</strong></h4><ul><li>Allows for precise, manual control over styling.</li><li>Useful when transitioning an app with existing CSS to MUI.</li></ul><h4><strong>Cons:</strong></h4><ul><li>Can cause naming conflicts and isn’t as manageable as styled() or sx.</li><li>Does not use the MUI theme system, making theme changes harder to apply consistently.</li></ul><h4><strong>When Not to Use:</strong></h4><ul><li>Avoid for large projects unless you already have a substantial CSS codebase.</li><li>Not recommended for apps where styles should be entirely theme-driven for consistency.</li></ul><h3>5. Component-Specific API Customization</h3><h4><strong>Best for:</strong></h4><ul><li>MUI components often have props for common customizations. For example, the Button component has props like variant, size, and color.</li><li>Using these props can help you quickly change component styles.</li></ul><pre>&lt;Button variant=&quot;contained&quot; color=&quot;secondary&quot; size=&quot;large&quot;&gt;<br>  Custom Button<br>&lt;/Button&gt;</pre><h4><strong>Pros:</strong></h4><ul><li>Simple to implement and relies on built-in MUI properties.</li><li>Does not require external CSS or complex configuration.</li></ul><h4><strong>Cons:</strong></h4><ul><li>Limited to predefined values and lacks custom styling flexibility.</li></ul><h4><strong>When Not to Use:</strong></h4><ul><li>Avoid for unique or custom designs that need advanced styling.</li><li>When using custom themes, if you need high control over appearance, go with styled() or theme overrides instead.</li></ul><h3>6. Using Emotion (for MUI v5+)</h3><ul><li>MUI v5 integrates with Emotion for styling, allowing you to create highly dynamic styles with JavaScript functions and conditional logic.</li><li>This approach is effective when you need styles that respond to various props or state changes.</li></ul><pre>import { css } from &#39;@emotion/react&#39;;<br><br>const dynamicStyle = css`<br>  background-color: #f44336;<br>  &amp;:hover {<br>    background-color: #d32f2f;<br>  }<br>`;<br><br>&lt;Button css={dynamicStyle}&gt;Dynamic Button&lt;/Button&gt;</pre><h4><strong>Best for:</strong></h4><ul><li>Highly dynamic or conditional styling that needs to be computed based on props or state.</li><li>Advanced styles that cannot be easily applied with the sx prop or styled() function alone.</li></ul><h4><strong>Pros:</strong></h4><ul><li>Provides highly flexible, conditional styling options.</li><li>Allows for complex styling logic directly within your component code.</li></ul><h4><strong>Cons:</strong></h4><ul><li>May complicate your component structure if used excessively.</li></ul><h4><strong>When Not to Use:</strong></h4><ul><li>Avoid if styles don’t require conditional logic, as styled() or sx can handle most use cases more cleanly.</li><li>Avoid overuse, as it can reduce readability and maintainability of your code.</li></ul><h3>Deprecated Approaches</h3><ul><li><strong>JSS Styling (in MUI v4)</strong>: JSS (the engine behind makeStyles) was deprecated in MUI v5 in favor of styled() and Emotion. MUI no longer recommends using JSS, as it can lead to inefficient style handling and lacks some modern styling features.</li><li><strong>Inline Styles</strong>: While not deprecated, inline styles are generally discouraged for anything beyond minor, one-off adjustments. They don’t integrate with the theme, which can lead to inconsistencies in the app’s look and feel.</li></ul><p>Each of these methods has unique strengths, but they work best when used in the right scenarios. For consistency, it’s often helpful to establish team guidelines around which customization method to use for specific styling needs.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fdfb81a74c2" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/mastering-material-ui-customization-in-react-best-practices-and-choosing-the-right-approach-9fdfb81a74c2">Mastering Material UI Customization in React: Best Practices and Choosing the Right Approach</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Trees : Traversals implementations simplified]]></title>
            <link>https://blog.stackademic.com/binary-trees-traversals-implementations-simplified-26aa1e93908b?source=rss-29613658adba------2</link>
            <guid isPermaLink="false">https://medium.com/p/26aa1e93908b</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[traversals]]></category>
            <category><![CDATA[binary-tree]]></category>
            <dc:creator><![CDATA[Sushmitha Dhummi Thrilochana]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 20:45:36 GMT</pubDate>
            <atom:updated>2024-11-06T05:35:52.226Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Mastering Binary Trees: Concepts, Traversals, and Problems</strong></h3><figure><img alt="Binary Tree — key operations simplified" src="https://cdn-images-1.medium.com/max/500/1*De3JFhWnW17LgX9SNLltJQ.png" /></figure><h3><strong>Contents</strong></h3><ol><li><a href="#fdbd"><strong>What is Tree? </strong></a><strong><br>- </strong><a href="#0705"><strong>Types of Trees</strong></a></li><li><a href="http://790c/"><strong>Depth First Search (DFS) Traversal</strong></a><strong>:<br>- </strong><a href="#4261"><strong>Pre-order</strong></a><strong> <em>( Node &gt; Left &gt; Right)</em><br>- </strong><a href="#dccd"><strong>In-order</strong></a><strong> <em>(Left &gt; Node &gt; Right)</em><br>- </strong><a href="#ae98"><strong>Post-order</strong></a><strong> <em>(Left &gt; Right &gt; Node)</em></strong></li><li><a href="#b10d"><strong>Breadth Frist Search (BFS) Traversal</strong></a><strong>: <em>Level-order traversal</em></strong></li><li><a href="#ea42"><strong>Summary</strong></a></li><li><a href="#2799"><strong>Practical exercises to master Binary Trees</strong></a><strong><br>- Find max depth of binary tree / height of a binary tree.<br>- Is binary tree symmetric.<br>- Lowest common ancestor of binary tree.<br>- Binary tree right side view.<br>- Construct Binary Tree from Inorder and Postorder Traversal</strong></li></ol><h3><strong>What is Tree?</strong></h3><p>A Tree is a hierarchical data structure where each element is a “node”.</p><p>Each node mainly comprises of 2 parts — <br>1. <strong>Data </strong>part holding a value .<br>2. <strong>Pointer </strong>part holding pointer/s to its children nodes.</p><p><strong>A node can be —</strong></p><ul><li><strong>Root </strong>— Top most node in the tree. <em>(Has no parent)</em></li><li><strong>Parent </strong>— Has one or more child nodes.<em> (Has a pointer to another node)</em></li><li><strong>Child </strong>— Has a parent node. <em>(Is being pointed by another node)</em></li><li><strong>Leaf </strong>— Has no child node <em>(Do not have pointer to another node</em>)</li><li><strong>Sibling </strong>— Has same parent node.</li></ul><p><strong>Other terminologies to know are</strong></p><ul><li><strong>Height</strong> — Longest path from Root node to a Leaf node. (number of levels)</li><li><strong>Depth of a node </strong>— Length of a node from Root node.</li><li><strong>Subtree </strong>— Part of tree consisting of a node and its descendants.</li></ul><blockquote>From a <strong>Graph’s view</strong>, Tree is a <strong>directed acyclic graph</strong> with <strong>N nodes </strong>and <strong>N-1 edges </strong>(where edge is the link between parent and child) . Note that, if the edges exceeds N-1 then there is a cycle and it is not a tree but simply a cyclic graph.</blockquote><h4><strong>Types of Trees:</strong></h4><p><strong>Some of the popular types are —</strong></p><ol><li><strong>N-ary Tree: </strong>A tree where each node can have at most N children.</li><li><strong>Binary Tree: </strong>Tree where each node has <em>at most 2 children</em> — <em>Left, Right</em></li><li><strong>Binary Search Tree: </strong>A binary tree that follows binary search property:<em> Left child &lt; Parent; Right child &gt; Parent</em>. (Read more <a href="https://medium.com/@sushmita.dt/binary-search-tree-implementation-3fb99c3a97c4">here</a>)</li><li><strong>Heap: </strong>A binary tree that follows the heap property: <em>MinHeap; MaxHeap</em></li><li><strong>Trie: </strong>A N-ary tree where each node is a string, also known as Prefix tree.</li></ol><h3><strong>Traversals</strong></h3><p>Traversals refers to the methods used to visit all the nodes in the tree systematically. There are several traversal methods, each serving different purposes and different ordering.</p><p>The 2 fundamental types of traversals are—<em> Depth First Search and Breadth First Search. </em>In this article, we will focus on standard methods to traverse in Binary Trees.</p><pre>// Definition for binary tree node<br>class TreeNode{<br>  constructor(value){<br>    this.val = value;<br>    this.left = null;<br>    this.right = null;<br>  }<br>}</pre><h4><strong>Depth First Search (DFS)</strong></h4><p>DFS explores as far down a branch as possible before backtracking. It can be implemented in three different orders: <em>Pre-order, In-order, and Post-order.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*Xv3LVj-No0GHKNvHj76MUA.png" /><figcaption><strong>Depth First Search Traversals</strong></figcaption></figure><h4><strong>1. Pre-order traversal</strong></h4><p>Visit the current node, then the left subtree, and finally the right subtree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*tIiMC9AD7F0L1aJMgl1JPA.png" /><figcaption><strong>DFS - Pre-order traversal</strong></figcaption></figure><pre>function preorderTraversal(root){<br>  let output = [];<br><br>  // Recursive function<br>  function traverse(node){<br>    if(node){<br>      output.push(node.val); // Visit node<br>      traverse(node.left);   // Traverse left subtree<br>      traverse(node.right);  // Traverse right subtree<br>    }<br>  }<br><br>  return output;<br>}</pre><h4><strong>2. In-order traversal</strong></h4><p>Visit the left subtree, then the current node, and finally the right subtree.</p><blockquote>In <a href="https://medium.com/@sushmita.dt/binary-search-tree-implementation-3fb99c3a97c4">binary search tree (BST)</a>, in-order traversal yields nodes in ascending order.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*U8drQt4SYNeoFRRhab6oaA.png" /><figcaption><strong>DFS — In-order traversal</strong></figcaption></figure><pre>function inorderTraversal(root){<br>  let output = [];<br><br>  function traverse(node){<br>    if(node){<br>      traverse(node.left);   // Traverse left subtree<br>      output.push(node.val); // Visit node      <br>      traverse(node.right);  // Traverse right subtree<br>    }<br>  }<br><br>  return output;<br>}</pre><h4><strong>3. Post-order traversal</strong></h4><p>Visit the left subtree, then the right subtree, and finally the current node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*-mJeqFL-G-zpXyqkO-ayBw.png" /><figcaption><strong>DFS - Post-order traversal</strong></figcaption></figure><pre>function inorderTraversal(root){<br>  let output = [];<br><br>  function traverse(node){<br>    if(node){<br>      traverse(node.left);   // Traverse left subtree<br>      traverse(node.right);  // Traverse right subtree<br>      output.push(node.val); // Visit node    <br>    }<br>  }<br><br>  return output;<br>}</pre><h4><strong>Breadth First Search (BFS)</strong></h4><p>In BFS, nodes are visited level by level from left to right. So it naturally process siblings and neighbors at one level before moving on to next level. It is also known as <strong>“level-order traversal”</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*W2v-vHvOWsGUYdqQiz40NA.png" /><figcaption><strong>BFS - level order traversal</strong></figcaption></figure><pre>// Recursive BFS Traversal<br>var levelOrder = function(root) {<br>    let levels = []<br>    // Pre-order traversal, but pushing node.val to level it belongs to<br>    function traverse(node, curlevel){<br>        if(node){<br>            if(curlevel==levels.length){<br>                levels.push([])<br>            }<br>            levels[curlevel].push(node.val);<br>            traverse(node.left,curlevel+1);<br>            traverse(node.right,curlevel+1);<br>        }<br>    }<br>    traverse(root,0)<br>    return levels;<br>};<br><br>// output: [[1],[2,3],[4,5,6],[7]]</pre><p>Iterative approach of BFS makes use of a <strong>Queue </strong>to keep track of nodes.</p><pre>// Iterative BFS traversal<br>function BFS ( root){<br>    const output = [];<br>    const queue = [];  <br>    queue.push(root);<br><br>    while (queue.length) {<br>      curNode = queue.shift();<br>      output.push(curNode.val);<br><br>      if (curNode.left) queue.push(curNode.left);<br>      if (curNode.right) queue.push(curNode.right);<br>    }<br><br>    return output;<br>  }<br><br>// output: [1, 2, 3, 4, 5, 6, 7]</pre><h3><strong>Summary</strong></h3><ul><li>Binary tree is a tree data structure, where each node can have <strong>at most 2 children </strong>— Left child, Right child.</li><li>Depth First Search (DFS) Traversal:<br>- <strong>In-Order:</strong> Left -&gt; Node -&gt; Right<br>- <strong>Pre-Order: </strong>Node -&gt; Left -&gt; Right<br>- <strong>Post-Order:</strong> Left -&gt; Right -&gt; Node</li><li><strong>Breadth First Search :</strong> Traverses level by level from top to bottom. Requires a queue for implementation.</li><li><strong>Time Complexity:</strong> <strong>O(N) </strong>for both DFS and BFS, as each node is visited exactly once in each traversal.</li></ul><h3><strong>Practical exercises to master Binary Trees</strong></h3><p>With traversal implementations covered, we’re now ready to apply our knowledge. Here are some basic binary tree problems to deepen your understanding and enhance problem-solving skills.</p><p><strong>1. Find max depth of binary tree / height of a binary tree</strong></p><p><strong>2. Is binary tree symmetric.</strong></p><p><strong>3. Lowest common ancestor of binary tree.</strong></p><p><strong>4. Binary tree right side view.</strong></p><p><strong>5. Construct Binary Tree from Inorder and Postorder Traversal</strong></p><p>Thanks for reading! 😊 I would love to learn your insights on Binary Trees in the comments!</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26aa1e93908b" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/binary-trees-traversals-implementations-simplified-26aa1e93908b">Binary Trees : Traversals implementations simplified</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Search Tree Implementation]]></title>
            <link>https://blog.stackademic.com/binary-search-tree-implementation-3fb99c3a97c4?source=rss-29613658adba------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fb99c3a97c4</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[binary-search-tree]]></category>
            <category><![CDATA[binary-search]]></category>
            <dc:creator><![CDATA[Sushmitha Dhummi Thrilochana]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 06:35:31 GMT</pubDate>
            <atom:updated>2024-11-06T05:35:58.552Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*mm8DzO-7Egd6WrwpsdGhAA.png" /></figure><h3>Table of Contents</h3><ol><li><a href="#0bc9"><strong>Introduction</strong></a></li><li><a href="#9f65"><strong>Operations</strong></a><br>- <a href="#00ba">Insert</a><br>- <a href="#766c">Search</a><br>- <a href="#99b5">Delete</a></li><li><a href="#35ce"><strong>Summary</strong></a></li></ol><p>Before diving into Binary Search Tree (BST), it is recommended to understand the <a href="https://medium.com/@sushmita.dt/binary-trees-traversals-implementations-simplified-26aa1e93908b"><strong>Binary Tree</strong></a> data structure first, because it is the foundation upon which more specialized trees, like BSTs, are built.</p><p>Basically, a Binary Tree is a hierarchical tree like data structure, where each node can have at most 2 children — <strong>Left child</strong>, <strong>Right child</strong>.</p><blockquote><em>On the other hand, a </em><strong><em>Binary </em>Search <em>Tree</em></strong><em> is a binary tree, which satisfies </em><strong>binary search property<em>,</em> </strong><em>where in</em> <strong>— </strong><br> ▪ <strong>Left child &lt; Parent <br> </strong>▪<strong> Right child &gt; Parent</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*MwSm_adRVzkwb554sUpEfg.png" /><figcaption>Fig 1: Binary Search Tree</figcaption></figure><p>Which means, each node in the BST always have a value that is greater than all values in its left subtree and less than all values in its right subtree.</p><p>This property facilitates quick search, insertion, and deletion operations.</p><blockquote>💡 <em>The </em><strong>In-order traversal</strong> of <strong>BST </strong>always give elements in an <strong>increasing </strong>order! <br><em>For ex., in-order traversal in above tree gives: </em>10, 15, 18, 20, 25, 30, 40.</blockquote><h3>Implementation</h3><p>Lets dive into the implementation of Binary Search Tree.</p><pre>// Node class<br>class Node{<br>  constructor(value){<br>    this.val = value;<br>    this.left = null;<br>    this.right = null;<br>  }<br>}<br><br>// Binary Search Tree class<br>class BST{<br>  constructor(){<br>    this.root = null;<br>  }<br><br>  // BST methods - insert, search, delete<br><br>}</pre><h4>1. Insert</h4><pre>class BST {<br>  constructor() {<br>    this.root = null;<br>  }<br><br>  // Insert Method<br>  insert(val) { <br><br>   // Recursive helper function to insert a value<br>   function insertRecursive(node) {<br>      // Base case<br>      if (node == null) {<br>        return new Node(val); // Insert new node<br>      }<br>      // Recursive case: Traverse the tree<br>      if (val &gt; node.val) {<br>        node.right = insertRecursive(node.right); // Go right<br>      } else {<br>        node.left = insertRecursive(node.left); // Go left<br>      }<br>      return node; // Return updated node<br>    }<br><br>    // Start insertion from the root<br>    this.root = insertRecursive(this.root);    <br>  }<br>  <br>}</pre><p>The recursion implementation is very straightforward :</p><ul><li><strong>Base Case</strong>: If the current node is null, we’ve found the correct spot in tree to insert the new value. So we create and return a new Node.</li><li><strong>Recursive Case</strong>: <em>Traverse the tree to find the correct position.</em><br>- If val&gt; node.val, go to right subtree (node.right).<br>- If val&lt;node.val, go to the left subtree (node.left).</li><li>After the recursive call, the current node is returned to ensure the tree structure is maintained. This is important to understand.</li><li><strong>Updating the Root</strong>: After defining the recursive insertRecursive function, we call it with this.root as the argument. The result is assigned back to this.root, which ensures that if the tree was empty initially, the new node becomes the root.</li></ul><h4>2. Search</h4><p>This method efficiently searches for a key in a Binary Search Tree (BST) by leveraging the tree&#39;s properties (left children are smaller, right children are larger).</p><p>The implementation is straight forward. Just need to work around the BST property that left&lt;parent and right&gt;parent.</p><pre>class BST {<br>  constructor() {<br>    this.root = null;<br>  }<br>  <br>  // Search method<br>  search(key) {<br>    let cur = this.root;  // Start from the root<br>    <br>   // Traverse the tree until you find the node or reach a null pointer<br>    while (cur !== null &amp;&amp; key !== cur.val) {<br>      if (key &gt; cur.val) {<br>        cur = cur.right; // Go right<br>      } else {<br>        cur = cur.left; // Go left<br>      }<br>    }<br><br>    return cur; // Return the found node or null if not found<br>  }<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9lMJMIav9vtLow_sHXHvw.png" /><figcaption>Fig 2: Binary Search Tree In-order traversal, successor, predecessor</figcaption></figure><h4>3. Delete</h4><p>Deletion operation is bit tricky compared to other operations, because we need to delete such that the BST property <em>(Left&lt;Parent; Right&gt;Parent) </em>is maintained.</p><p>Deletion in BST presents 3 cases, based on node that is being deleted —</p><ol><li><strong>It is a Leaf Node, has no child:</strong> Simply delete the node, setting it to null</li><li><strong>It has right child</strong>: Copy value of its in-order <strong>successor. </strong>Delete successor.</li><li><strong>It has no right child, but has a left child</strong>: Copy value of its in-order <strong>predecessor.</strong> Delete predecessor</li></ol><blockquote><strong>Remember:</strong> In-order traversal of BST gives values sorted in ascending order.</blockquote><p>The “<strong>in-order successor”</strong> of a node in BST is the <strong>next node</strong> in the in-order traversal of the BST. To find successor, go to right child node once and then go to left child nodes until the end. It is the <em>leftmost node of the </em><strong><em>right subtree </em></strong>of a node. This will get the next smallest value greater than the node.</p><p>The <strong>“in-order predecessor”</strong> of a node in BST is the <strong>previous node</strong> in the in-order traversal of the BST. To find predecessor, go to left child node once and then go to right child nodes until the end. It is the<em> rightmost node of the </em><strong><em>left subtree</em></strong>. This will get the next greatest value smaller than the node.</p><pre>// Implementation of Delete method of BST<br>class BST {<br>  constructor() {<br>    this.root = null;<br>  }<br><br>  // Delete method - to remove a node with the given key<br>  delete(key) {<br><br>    function getSuccessor(node) {<br>      // Go right once, then all the way left (smallest in right subtree)<br>      node = node.right;<br>      while (node.left) {<br>        node = node.left;<br>      }<br>      return node;<br>    }<br><br>    function getPredecessor(node) {<br>      // Go left once, then all the way right (largest in left subtree)<br>      node = node.left;<br>      while (node.right) {<br>        node = node.right;<br>      }<br>      return node;<br>    }<br>    <br>    function _delete(node, value) {<br>      // Base case: empty tree or end of recursion<br>      if (node == null) return null;<br><br>      // Recursive case: Traverse BST for value<br>      if (value &gt; node.val) {<br>        node.right = _delete(node.right, value); // Recur to the right subtree<br>      } <br>      else if (value &lt; node.val) {<br>        node.left = _delete(node.left, value); // Recur to the left subtree<br>      } <br>      else { <br>        // Node with the value found<br>        // Case 1: Node is a leaf<br>        if (!node.left &amp;&amp; !node.right) {<br>          node = null;<br>        } <br>        // Case 2: Node with right child - find and replace with successor<br>        else if (node.right) {<br>          let successor = getSuccessor(node);<br>          node.val = successor.val; <br>          node.right = _delete(node.right, successor.val); // Delete successor<br>        } <br>        // Case 3: Node with only left child - replace with predecessor<br>        else {<br>          let predecessor = getPredecessor(node);<br>          node.val = predecessor.val;<br>          node.left = _delete(node.left, predecessor.val); // Delete predecessor<br>        }<br>      }<br>      return node; // Return the modified node<br>    }<br>    this.root = _delete(this.root, key); // Start the deletion process from the root<br>  }<br>}</pre><h3>Summary</h3><ol><li>BST is binary tree where <strong><em>Left child &lt; Parent</em></strong><em> </em>and <strong><em>Right child &gt; Parent</em></strong>.</li><li><strong>In-order traversal</strong> of BST gives array sorted in ascending order.</li><li>Insert and Search operation is straight forward, just need to work with BST property (point 1).</li><li><strong>Deletion </strong>in BST, you must know which node to replace after deleting. <br>3 cases arises — <br>1) If you are deleting <strong><em>Leaf node:</em></strong> Simply null it. No strings attached!<br>2) <strong><em>Has a right child:</em></strong> Replace with in-order successor value.<br>3) <strong><em>Has no right, got left child only:</em></strong> Replace with in-order predecessor.</li><li><strong>Successor </strong>of a node in BST — next node in the in-order traversal, and it is the <strong><em>smallest node (leftmost) </em></strong><em>in the</em><strong><em> right subtree</em></strong>.</li><li><strong>Predecessor </strong>of a node — previous node in the in-order traversal, and it is the <strong><em>largest node (rightmost) </em></strong><em>in the</em><strong><em> left subtree</em></strong>.</li><li><strong>Time complexity</strong> for insert, search and delete operations is O(log n)in the average case, and O(n)in the worst case, where n is the number of nodes in the tree.</li><li>BSTs are used in scenarios where data needs to be stored in a way that allows efficient searching and sorting, like in databases, file systems, routing tables, data compressions, etc.</li></ol><p>Thanks for reading! 😊 Feel free to share your insights about Binary Search Tree in the comments.</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fb99c3a97c4" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/binary-search-tree-implementation-3fb99c3a97c4">Binary Search Tree Implementation</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Fast AI Content Authentication Using Parallel Distributed Computing Architecture]]></title>
            <link>https://medium.com/@sushmita.dt/a-fast-ai-content-authentication-using-parallel-distributed-computing-architecture-3cd09ea0ba70?source=rss-29613658adba------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cd09ea0ba70</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[deepfakes]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[content-authenticity]]></category>
            <dc:creator><![CDATA[Sushmitha Dhummi Thrilochana]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 06:25:00 GMT</pubDate>
            <atom:updated>2024-02-26T18:09:34.255Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.linkedin.com/in/sushmitha-dt/"><em>Sushmitha</em></a><em>, Intern, Adori Labs, Santa Clara, California</em></p><p>In an age of rapidly evolving AI generated content and sophisticated deep fakes, creators face an unprecedented challenge: <strong>safeguarding ownership and authenticity</strong>. Addressing the AI risks and safety, the White House recently released an Executive Order* underscoring the need for robust media authentication to guarantee authenticity and integrity.</p><p><a href="https://www.adorilabs.com/"><strong>Adori Labs</strong></a>* has a patented <a href="https://www.adorilabs.com/ai">audio watermark technology</a> to combat these challenges.</p><blockquote>Adori’s watermarking solution effectively authenticates ownership and empowers creators by imperceptibly encoding the creator’s unique ID into the audio that is capable of surviving any manipulations on the media.</blockquote><p>As a software engineering intern, I had the distinct opportunity to develop an AI content authentication software using their watermark technology with guidance of the <a href="https://www.linkedin.com/in/nathan-iyer-4587141/"><em>CEO of Adori Labs, Nathan Iyer</em>,</a> who architected the design.</p><p>This application aims to simplify and streamline the content authentication process for users while ensuring robust scalability and efficiency.</p><h3>The Key Challenges</h3><p>Building this application for production, exposed a number of workflow problems that need an elegant solution. Some of these challenges are listed below:</p><ol><li><strong>Scalability</strong>: The backend should be capable of handling large volumes of diverse audio and video file formats.</li><li><strong>Speed or Performance</strong>: Watermarking is a computing intensive task. However, creators want this to happen quickly, without having to wait for a long time for publication of their content.</li><li><strong>Simplified workflow: </strong>The application needed a simple user experience wherein users can upload multiple files, view a progress for each file, and a notification needs to be sent to the user after it is done with a download link.</li><li><strong>Cost:</strong> The solution needs to be cost effective.</li></ol><h3>The Solution</h3><h4>A Parallel Approach: Splitting the Burden</h4><p>The answer to these challenges lay in parallelization. We split large files into smaller parts, encoding each parallelly using Amazon’s serverless Lambda service. This ensured speed and minimised user wait times. The files are then stitched together and uploaded to a S3 bucket.</p><h4>Diving into Architecture: A Serverless Symphony</h4><p>To achieve this parallel processing efficiently, we adopted a “<strong><em>Distributed Serverless Event-driven</em></strong>” architecture using Amazon Web Services (AWS).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xusKyfOL02vIqgPDLmEtg.png" /><figcaption><strong>Figure 1: Serverless, Event-Driven, Distributed Architecture</strong></figcaption></figure><p>Here’s the flow:</p><ol><li><strong>User uploads a file:</strong> It lands in an S3 bucket, triggering an event to Lambda function.</li><li><strong>Lambda checks file duration:</strong> If long, it splits the file into parts and uploads them to another S3 bucket.</li><li><strong>Each part triggers another Lambda function:</strong> AWS Lambda scales automatically, spinning up new instances to handle multiple uploads simultaneously.</li><li><strong>Parallel encoding:</strong> Each Lambda function encodes its assigned part.</li><li><strong>Merging the encoded parts</strong>: Once all parts are encoded, the final Lambda merges them back into a single file.</li><li><strong>Email notification:</strong> Upon completion, an email with the download link is sent to the user.</li><li><strong>Delete parts from S3: </strong>The split parts are no longer needed and can be deleted.</li></ol><blockquote><strong>The advantages of this architecture include</strong></blockquote><blockquote><strong>✔ Scalability: </strong>Automatic scaling handles large uploads effortlessly.<br><strong>✔ Speed:</strong> Parallelization ensures fast encoding, reducing user wait times.<br><strong>✔ Cost-effectiveness:</strong> Serverless pay-per-use model keeps costs low.</blockquote><h3>The Application in Action:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9CuojjqeOJZWJjSydap6Ww.gif" /><figcaption><strong>Figure 2: Encoding creator’s watermark into the files</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbpWgse9zqsYm6hDUKHEkQ.gif" /><figcaption><strong>Figure 3: Decoding the watermark from the file</strong></figcaption></figure><h3>Other Potential Applications</h3><p>The core approach of splitting large tasks, parallel processing with serverless functions, and event-driven triggering holds potential for various use cases beyond this specific project.</p><p>Other potential use cases may include -</p><ol><li><strong>Training AI models:</strong> Large datasets necessitate efficient processing. Splitting them into smaller chunks and utilizing parallel processing with Lambda functions can significantly reduce training times.</li><li><strong>Data processing pipelines:</strong> Breaking down complex data processing tasks into smaller, independent steps triggered by events (e.g., data arrival) creates a scalable and manageable pipeline.</li><li><strong>Image/video processing:</strong> Similar to audio watermarking, image/video resizing, manipulation, or feature extraction can benefit from parallel processing on smaller segments.</li><li><strong>Log analysis:</strong> Processing large log files in real-time for fraud detection, anomaly detection, or security analysis can be optimized through this architecture.</li></ol><p><em>My internship with Adori Labs was more than just a technical learning experience; it was a chance to contribute to a solution that empowers creators and tackles a critical challenge in the digital age. I am immensely grateful to Nathan Iyer and the talented team at Adori Labs for this opportunity, and I look forward to applying the knowledge and skills gained to future endeavors.</em></p><p>Cheers, thanks for reading! 😊</p><h3>References</h3><ol><li><a href="https://www.whitehouse.gov/briefing-room/statements-releases/2023/10/30/fact-sheet-president-biden-issues-executive-order-on-safe-secure-and-trustworthy-artificial-intelligence/">https://www.whitehouse.gov/briefing-room/statements-releases/2023/10/30/fact-sheet-president-biden-issues-executive-order-on-safe-secure-and-trustworthy-artificial-intelligence/</a></li><li><a href="https://www.adorilabs.com/">https://www.adorilabs.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cd09ea0ba70" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>