<?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 Abhishek Kr on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Kr on Medium]]></description>
        <link>https://medium.com/@abhishek.kr121?source=rss-e3ded9bf3de0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Abhishek Kr on Medium</title>
            <link>https://medium.com/@abhishek.kr121?source=rss-e3ded9bf3de0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:19:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhishek.kr121/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[High-performance rate limiter using ring buffers]]></title>
            <link>https://medium.com/@abhishek.kr121/high-performance-rate-limiter-using-ring-buffers-2e39a71de8a4?source=rss-e3ded9bf3de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e39a71de8a4</guid>
            <category><![CDATA[ring-buffer]]></category>
            <category><![CDATA[rate-limiter]]></category>
            <dc:creator><![CDATA[Abhishek Kr]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 15:26:29 GMT</pubDate>
            <atom:updated>2026-03-16T15:26:29.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZjOntexZdTpBRlRQEFA-1g.png" /></figure><p>A <strong>high-performance rate limiter using ring buffers</strong> is useful when you want <strong>very low latency and minimal locking</strong>, similar to techniques used in high-performance systems like packet processors and messaging systems.</p><p>This idea is conceptually similar to designs used in systems like:</p><ul><li>DPDK (lock-free ring queues for packet processing)</li><li>LMAX Disruptor (high-throughput event processing)</li><li>Apache Kafka (log structured ring-like append model)</li></ul><p>We want to avoid <strong>heavy Redis counters or database writes per request</strong>.</p><h3>1. Core Idea</h3><p>Instead of storing request timestamps in a list or database, we use a <strong>circular array (ring buffer)</strong>.</p><pre>Window = 10 seconds<br>Resolution = 1 second<br><br>Ring buffer size = 10</pre><pre>Index:   0 1 2 3 4 5 6 7 8 9<br>Counts:  5 3 2 7 4 1 0 0 0 0</pre><p>Each slot represents <strong>requests in that second</strong>.</p><p>When time moves forward, the buffer <strong>overwrites old slots automatically</strong>.</p><p>This makes it <strong>O(1)</strong> operations.</p><h3>2. How Request Processing Works</h3><p>For every request:</p><h4>Step 1 — Determine slot</h4><pre>slot = current_time % window_size</pre><p>Example:</p><pre>current_time = 105<br>window_size = 10<br><br>slot = 105 % 10 = 5</pre><h4>Step 2 — Reset slot if old</h4><p>Each slot keeps a timestamp.</p><pre>if slot.timestamp != current_second:<br>    slot.count = 0<br>    slot.timestamp = current_second</pre><p><strong>Step 3 — Increment request counter</strong></p><pre>slot.count++</pre><p><strong>Step 4 — Calculate total requests in window</strong></p><pre>total = sum(all slots)</pre><p>If</p><pre>total &gt; limit</pre><p>→ reject request.</p><h3>3. Ring Buffer Layout</h3><p>Efficient memory structure:</p><pre>struct Slot {<br>    uint64 timestamp<br>    uint32 count<br>}</pre><p>Ring:</p><pre>Slot buffer[WINDOW_SIZE]</pre><p>Example:</p><pre>WINDOW_SIZE = 60</pre><p>Memory:</p><pre>60 * 16 bytes ≈ 960 bytes per key</pre><p>Very small.</p><h3>4. Lock-Free Multi-Thread Design</h3><p>Use <strong>atomic increments</strong>.</p><pre>atomic_add(slot.count, 1)</pre><p>Avoid global locks.</p><p>Possible improvements:</p><pre>per-core buffers</pre><p>Example:</p><pre>core0 -&gt; ring0<br>core1 -&gt; ring1<br>core2 -&gt; ring2</pre><p>Total requests = sum of all rings.</p><p>This technique is used by <strong>ultra-low latency systems</strong>.</p><h3>5. Example C++ Implementation</h3><pre>#include &lt;atomic&gt;<br>#include &lt;vector&gt;<br>#include &lt;ctime&gt;<br><br>struct Slot {<br>    std::atomic&lt;uint64_t&gt; timestamp;<br>    std::atomic&lt;uint32_t&gt; count;<br>};<br><br>class RateLimiter {<br>private:<br>    int window;<br>    int limit;<br>    std::vector&lt;Slot&gt; ring;<br><br>public:<br>    RateLimiter(int w, int l) : window(w), limit(l), ring(w) {}<br><br>    bool allow() {<br>        uint64_t now = time(NULL);<br>        int slot = now % window;<br><br>        Slot &amp;s = ring[slot];<br><br>        uint64_t ts = s.timestamp.load();<br><br>        if (ts != now) {<br>            s.timestamp.store(now);<br>            s.count.store(0);<br>        }<br><br>        s.count.fetch_add(1);<br><br>        uint32_t total = 0;<br><br>        for (auto &amp;slot : ring) {<br>            total += slot.count.load();<br>        }<br><br>        return total &lt;= limit;<br>    }<br>};</pre><h3>6. Why Ring Buffer is Fast</h3><p>Operations are:</p><pre>O(1) memory access<br>O(1) increment</pre><p>No:</p><ul><li>heap allocation</li><li>database</li><li>network calls</li><li>heavy locks</li></ul><p>Perfect for:</p><pre>100k–1M requests/sec</pre><h3>7. Scaling for Distributed Systems</h3><p>Single node ring buffer works only locally.</p><p>Production systems combine:</p><pre>Local ring limiter<br>+<br>Distributed limiter</pre><p>Architecture:</p><pre>Client<br>  │<br>API Gateway<br>  │<br>Local Ring Buffer (fast)<br>  │<br>Redis / global limiter<br>  │<br>Backend</pre><p>Flow:</p><ol><li>Local limiter drops obvious spikes</li><li>Global limiter ensures fairness</li></ol><h3>8. Extremely High Performance Design (Millions RPS)</h3><p>Production architecture:</p><pre>Load Balancer<br>                 │<br>          ┌──────┴───────┐<br>          │              │<br>      Gateway1       Gateway2<br>          │              │<br>   Local Ring       Local Ring<br>     Limiter          Limiter<br>          │              │<br>       Redis Cluster / Global Counter</pre><p>Local limiter removes <strong>90% of spikes</strong>.</p><h3>9. Why This Design is Used in High-Performance Systems</h3><p>Conceptually similar to:</p><ul><li>DPDK ring queues</li><li>LMAX Disruptor event rings</li><li>Apache Kafka append log buffers</li></ul><p>All avoid <strong>locks and dynamic allocation</strong>.</p><h3>10. Advanced Optimization (Used in Trading Systems)</h3><p>Instead of summing the entire ring every request:</p><p>Maintain <strong>rolling total</strong>.</p><pre>total += 1<br>total -= expired_slot_count</pre><p>Now request check becomes:</p><pre>O(1)</pre><p>No loop required.</p><p>✅ <strong>Final benefit</strong></p><p>Ring buffer rate limiter:</p><pre>Latency: &lt; 1 microsecond<br>Memory: very small<br>Throughput: millions requests/sec<br>Locking: minimal</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e39a71de8a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Categories of Design Patterns]]></title>
            <link>https://medium.com/@abhishek.kr121/categories-of-design-patterns-8867ebd8d2a8?source=rss-e3ded9bf3de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8867ebd8d2a8</guid>
            <dc:creator><![CDATA[Abhishek Kr]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 07:34:06 GMT</pubDate>
            <atom:updated>2025-06-13T07:34:06.522Z</atom:updated>
            <content:encoded><![CDATA[<p>Here is a <strong>comprehensive list</strong> that includes:</p><h3>1. GoF (Gang of Four) Design Patterns (23 total)</h3><h3>Creational (5)</h3><ul><li>Singleton</li><li>Factory Method</li><li>Abstract Factory</li><li>Builder</li><li>Prototype</li></ul><h3>Structural (7)</h3><ul><li>Adapter</li><li>Bridge</li><li>Composite</li><li>Decorator</li><li>Facade</li><li>Flyweight</li><li>Proxy</li></ul><h3>Behavioral (11)</h3><ul><li>Chain of Responsibility</li><li>Command</li><li>Interpreter</li><li>Iterator</li><li>Mediator</li><li>Memento</li><li>Observer</li><li>State</li><li>Strategy</li><li>Template Method</li><li>Visitor</li></ul><h3>2. Concurrency Patterns (used in multithreading, I/O, distributed systems)</h3><pre>| Pattern                | Description                                                                                                  |<br>| ---------------------- | ------------------------------------------------------------------------------------------------------------ |<br>| Reactor                | Demultiplexes I/O events and dispatches to appropriate handler (event loop). Example: `epoll`, `libevent`.   |<br>| Proactor               | Handles asynchronous operations with completion callbacks (OS notifies you when done). Used in Windows IOCP. |<br>| Thread Pool            | Manages a pool of worker threads to execute tasks.                                                           |<br>| Active Object          | Decouples method execution from method invocation in concurrent systems.                                     |<br>| Future/Promise         | Represents a result that may become available later.                                                         |<br>| Scheduler              | Manages order and concurrency of tasks.                                                                      |<br>| Guarded Suspension     | Allows threads to wait until a condition is true.                                                            |<br>| Read-Write Lock        | Multiple readers allowed, exclusive write.                                                                   |<br>| Double-Checked Locking | Optimized Singleton or cache access.                                                                         |<br>| Monitor Object         | Encapsulates locks and condition variables.                                                                 |</pre><h3>3. <strong>Architectural Patterns</strong></h3><pre>| Pattern                             | Description                                                  |<br>| ----------------------------------- | ------------------------------------------------------------ |<br>| Model-View-Controller (MVC)         | Separates UI, logic, and data.                               |<br>| Model-View-ViewModel (MVVM)         | Variation of MVC (used in frontend frameworks like Angular). |<br>| Microservices                       | System as a suite of independently deployable services.      |<br>| Layered (n-tier)                    | Organizes system into layers (UI, business logic, data).     |<br>| Event-Driven                        | Uses publish-subscribe or event queues.                      |<br>| Pipes and Filters                   | Data flows through filters via pipelines.                    |<br>| Broker                              | Manages communication between components.                    |<br>| Client-Server                       | Distributed systems: client requests, server responds.       |<br>| Service-Oriented Architecture (SOA) | Services interact over a network using protocols.            |<br>| Hexagonal (Ports and Adapters)      | Isolates core logic from external dependencies.              |</pre><h3>4. <strong>Enterprise Application Patterns</strong> (from Fowler &amp; others)</h3><pre>| Pattern                                         | Description                                                     |<br>| ----------------------------------------------- | --------------------------------------------------------------- |<br>| Unit of Work                                    | Tracks changes to objects and persists them in one transaction. |<br>| Repository                                      | Encapsulates storage, retrieval, and query logic.               |<br>| Data Mapper                                     | Maps between in-memory objects and database tables.             |<br>| Domain Model                                    | Rich object model with business logic.                          |<br>| Service Layer                                   | Defines application’s operations.                               |<br>| DTO (Data Transfer Object)                      | Simplifies data passed between layers or services.              |<br>| CQRS (Command Query Responsibility Segregation) | Separates read and write models.                                |<br>| Event Sourcing                                  | Stores state as a series of events.                             |<br>| Saga                                            | Manages distributed transactions across services.               |</pre><h3>5. Enterprise Integration Patterns (EIP)</h3><p><strong>From the book by Gregor Hohpe and Bobby Woolf</strong> — useful in distributed systems and message-driven apps.</p><pre>| Pattern              | Use Case                              |<br>| -------------------- | ------------------------------------- |<br>| Message Channel      | Communication path between apps       |<br>| Message Broker       | Route, transform, or split messages   |<br>| Message Filter       | Filter messages based on criteria     |<br>| Content-Based Router | Route messages based on content       |<br>| Aggregator           | Combine multiple messages into one    |<br>| Splitter             | Split one message into parts          |<br>| Idempotent Receiver  | Ensure message is processed only once |<br>| Message Translator   | Convert message format                |</pre><h3>6. <strong>Cloud / Distributed System Patterns</strong> (From Microsoft, AWS, etc.)</h3><pre>| Pattern                    | Purpose                                  |<br>| -------------------------- | ---------------------------------------- |<br>| Circuit Breaker            | Prevent cascading failures               |<br>| Retry                      | Retry failed operations                  |<br>| Bulkhead                   | Isolate faults in service domains        |<br>| Throttling                 | Control load on resources                |<br>| Leader Election            | Select a master in distributed systems   |<br>| Scheduler Agent Supervisor | Recover failed tasks                     |<br>| Sidecar                    | Deploy helper containers beside main app |<br>| Ambassador                 | Outbound proxy container pattern         |<br>| Service Discovery          | Find services dynamically                |<br>| Strangler Fig              | Gradually replace old system with new    |</pre><p>Common in <strong>Kubernetes</strong>, <strong>Service Meshes (Istio, Linkerd)</strong>, <strong>AWS</strong>, <strong>Azure</strong>, etc.</p><h3>7. <strong>Data Patterns / ETL &amp; Analytics</strong></h3><pre>| Pattern                   | Purpose                            |<br>| ------------------------- | ---------------------------------- |<br>| Event Sourcing            | Store changes as events            |<br>| CQRS                      | Separate read/write models         |<br>| Data Lake / Lakehouse     | Store structured/unstructured data |<br>| Data Sharding             | Scale DBs horizontally             |<br>| Change Data Capture (CDC) | Track DB changes for ETL           |</pre><p>Used in <strong>Kafka</strong>, <strong>Debezium</strong>, <strong>Apache Flink</strong>, <strong>Spark</strong>, <strong>ClickHouse</strong>, <strong>Snowflake</strong>, etc.</p><h3>8. <strong>DevOps &amp; Infrastructure Patterns</strong></h3><pre>| Pattern                       | Purpose                             |<br>| ----------------------------- | ----------------------------------- |<br>| Immutable Infrastructure      | Never update in-place               |<br>| Blue-Green Deployment         | Seamless version rollout            |<br>| Canary Release                | Rollout new version to subset       |<br>| Infrastructure as Code        | Declarative infra setup (Terraform) |<br>| Configuration Drift Detection | Detect unexpected changes           |</pre><h3><strong>9. AI / ML System Design Patterns</strong></h3><pre>| Pattern                  | Use                                         |<br>| ------------------------ | ------------------------------------------- |<br>| Feature Store            | Centralized feature storage                 |<br>| Online/Offline Inference | Different serving latency paths             |<br>| Model Registry           | Track and version models                    |<br>| Shadow Mode              | Run new models silently to observe behavior |<br>| Feedback Loop            | Auto-retrain based on new data              |</pre><h3><strong>10. Functional Patterns</strong> (Used in Haskell, Scala, etc.)</h3><pre>| Pattern        | Purpose                                             |<br>| -------------- | --------------------------------------------------- |<br>| Monad          | Encapsulate computation with context                |<br>| Functor        | Map over context                                    |<br>| Currying       | Transform multi-arg function into single-arg chains |<br>| Pure Functions | No side effects                                     |<br>| Immutability   | Prevent state change                                |</pre><h3>11. Testing Patterns</h3><pre>| Pattern                         | Use                                 |<br>| ------------------------------- | ----------------------------------- |<br>| Test Doubles (Mock, Stub, Fake) | Isolate unit tests                  |<br>| Given-When-Then (Gherkin)       | BDD test structure                  |<br>| Fixture                         | Known test state setup              |<br>| Golden Master                   | Snapshot test outputs               |<br>| Test Pyramid                    | Ratio of unit/integration/e2e tests |</pre><h3>Summary Table:</h3><pre>| Category                | Examples                             |<br>| ----------------------- | ------------------------------------ |<br>| GoF Patterns            | Singleton, Strategy, Observer        |<br>| Concurrency Patterns    | Reactor, Proactor, Thread Pool       |<br>| Architectural Patterns  | MVC, Microservices, Ports &amp; Adapters |<br>| Enterprise Integration  | Message Broker, Router, Aggregator   |<br>| Distributed Systems     | Circuit Breaker, Leader Election     |<br>| Data/Streaming Patterns | CQRS, Event Sourcing, CDC            |<br>| DevOps Patterns         | Blue-Green, IaC, Canary              |<br>| AI/ML Patterns          | Feature Store, Online Inference      |<br>| Functional Patterns     | Monad, Currying, Immutability        |<br>| Testing Patterns        | Mocks, Fixtures, Golden Master       |</pre><h3>Real-World Pattern Mapping</h3><p>- Nginx: Reactor pattern</p><p>- Kafka: Event-Driven, EIP (Message Channel, Topic, Broker)</p><p>- Elasticsearch: Thread Pool + Bulkhead</p><p>- Istio: Sidecar, Ambassador, Service Mesh</p><p>- Boost.Asio: Proactor</p><p>- Redis Sentinel: Leader Election</p><ul><li>Kubernetes: Declarative IaC, Service Discovery, Controller pattern</li></ul><h3>Domain-Specific Patterns — High-Performance Server</h3><p>-Reactor or Proactor for event-driven I/O</p><p>- Thread Pool for concurrent request processing</p><p>- Flyweight and Object Pooling for memory efficiency</p><p>- Builder for configuration objects</p><p>- Observer for metrics/event notification</p><p>- State pattern for connection states</p><p>- Command for task abstraction (task queues)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8867ebd8d2a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns for Connection Handling]]></title>
            <link>https://medium.com/@abhishek.kr121/core-design-patterns-for-connection-handling-8130e72f57fc?source=rss-e3ded9bf3de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8130e72f57fc</guid>
            <dc:creator><![CDATA[Abhishek Kr]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 03:18:36 GMT</pubDate>
            <atom:updated>2025-06-11T06:11:48.966Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Reactor Pattern</h3><p><strong>📌 Role</strong>: Handles <strong>I/O readiness events</strong> (e.g., epoll, select, kqueue).</p><p><strong>🧠 Concept</strong>:</p><ul><li>A <strong>single thread or loop</strong> waits for events.</li><li>When a socket is readable/writable, the reactor notifies the corresponding handler.</li></ul><p><strong>📐 Structure</strong>:</p><ul><li>Reactor: Event demultiplexer (epoll_wait, etc.)</li><li>EventHandler: Abstract interface for handling events.</li><li>ConcreteHandler: Registered per socket.</li></ul><p><strong>✅ Use in Libraries</strong>: Boost.Asio (with custom handlers), libevent, libuv.</p><h3>2. Proactor Pattern</h3><p><strong>📌 Role</strong>: Handles <strong>completion events</strong>, typically for <strong>asynchronous I/O</strong>.</p><p><strong>🧠 Concept</strong>:</p><ul><li>System (kernel or runtime) completes I/O in the background.</li><li>Application is notified <em>after</em> the operation completes.</li></ul><p><strong>🔄 Difference from Reactor</strong>:</p><ul><li><strong>Reactor</strong>: App initiates I/O <em>after readiness</em>.</li><li><strong>Proactor</strong>: App is notified <em>after completion</em>.</li></ul><p><strong>✅ Use in Libraries</strong>: Windows IOCP, Boost.Asio (on Windows), libuv (for some ops)</p><h3>3. Thread Pool Pattern</h3><p><strong>📌 Role</strong>: Avoid creating a thread per request.</p><p><strong>🧠 Concept</strong>:</p><ul><li>A fixed number of worker threads consume tasks from a queue.</li><li>Useful for CPU-bound or blocking operations (e.g., DB calls, file I/O).</li></ul><p><strong>📐 Structure</strong>:</p><ul><li>ThreadPool: Manages threads and task queue.</li><li>Task: Encapsulated unit of work.</li></ul><p><strong>✅ Integration</strong>:</p><ul><li>Combine with Reactor: Reactor receives events → dispatches task to ThreadPool.</li><li>Combine with Proactor: Completion handler pushes task to ThreadPool.</li></ul><h3>4. Acceptor-Connector Pattern</h3><p><strong>📌 Role</strong>: Cleanly separate connection acceptance and request handling.</p><p><strong>🧠 Concept</strong>:</p><ul><li>Acceptor: Listens for new connections.</li><li>Connector/Handler: Manages communication with a client.</li></ul><p><strong>✅ Use</strong>: In modular servers that support connection reuse, backends, or pools.</p><h3>5. Chain of Responsibility / Middleware</h3><p><strong>📌 Role</strong>: For layered request/response handling.</p><p><strong>🧠 Concept</strong>:</p><ul><li>Each handler in the chain can inspect/modify the request or response.</li><li>Useful for auth, logging, rate limiting, etc.</li></ul><h3>6. State Pattern</h3><p><strong>📌 Role</strong>: For stateful protocols (like HTTP keep-alive, WebSockets).</p><p><strong>🧠 Concept</strong>:</p><ul><li>Each connection can be in a state: Reading, Parsing, Responding, Closed.</li><li>Each state has a handler for transitions.</li></ul><h3>🧱 Combined Architecture Diagram</h3><pre>+-----------------------------+<br>|       Main Event Loop      |  (Reactor or Proactor)<br>|  (epoll_wait / IOCP / kqueue)<br>+-------------+---------------+<br>              |<br>     [socket is ready / op completed]<br>              |<br>              v<br>+-----------------------------+<br>|      Connection Handler     |  (Handles read/write or delegates)<br>+-----------------------------+<br>              |<br>              v<br>+-----------------------------+     +------------------------+<br>|        Thread Pool          |&lt;---&gt;|   Business Logic Task   |<br>| (Executes handlers/tasks)   |     | (DB, compute, etc.)     |<br>+-----------------------------+     +------------------------+<br>              |<br>              v<br>+-----------------------------+<br>|       Response Writer       |<br>+-----------------------------+</pre><h3>🧰 Suggested Libraries for Each Pattern</h3><pre>| Pattern     | C++ Library/Tool                                                     | Notes                                                |<br>| ----------- | -------------------------------------------------------------------- | ---------------------------------------------------- |<br>| Reactor     | `epoll`, `boost::asio`, `libevent`, `libuv`                          | Most Unix/Linux-based servers                        |<br>| Proactor    | `IOCP` (Windows), `boost::asio`                                      | More common in Windows or Boost.Asio abstracted form |<br>| Thread Pool | `std::thread + queue`, `boost::asio::thread_pool`, `concurrentqueue` | Standard multi-threaded workloads                    |<br>| Acceptor    | `boost::asio::ip::tcp::acceptor`                                     | Clean abstraction for TCP servers                    |</pre><h3>✅ Best Scalable Patterns for TCP Connections</h3><pre>| Pattern                                        | Scalability       | Description                                                                |<br>| ---------------------------------------------- | ----------------- | -------------------------------------------------------------------------- |<br>| **Reactor + Thread Pool**                      | ⭐⭐⭐⭐⭐ (Excellent) | Efficient I/O event loop with multithreaded request processing.            |<br>| **Proactor + Thread Pool**                     | ⭐⭐⭐⭐ (Very Good)  | Especially scalable on Windows or if I/O completion is natively supported. |<br>| **Asynchronous Non-blocking I/O + Event Loop** | ⭐⭐⭐⭐⭐ (Excellent) | Linux-style `epoll` or `kqueue` is extremely scalable for 10k+ sockets.    |</pre><h3>🔍 Why Reactor + Thread Pool is Most Scalable (Especially on Linux)</h3><h3>📌 Key Strengths:</h3><ul><li><strong>Single-threaded I/O loop (Reactor)</strong> handles thousands of sockets (via epoll, kqueue, or libevent).</li><li><strong>Thread pool</strong> offloads CPU-bound work (e.g., parsing, DB access).</li><li><strong>Non-blocking I/O</strong> ensures no thread is stuck on a socket read/write.</li></ul><h3>🧠 Real-World Use:</h3><ul><li><strong>Nginx</strong> (uses Reactor)</li><li><strong>Redis</strong> (single-threaded event loop with non-blocking I/O)</li><li><strong>Netty (Java)</strong> — popular server framework uses Reactor pattern</li><li><strong>Node.js</strong> — single-threaded event loop + async callbacks (Reactor)</li></ul><h3>🖼️ Architecture: Reactor + ThreadPool (Highly Scalable)</h3><pre>          +-------------------------+<br>          |     epoll_wait() loop   |  &lt;---- Reactor (1 thread)<br>          +-----------+-------------+<br>                      |<br>       [socket ready for read/write]<br>                      |<br>                      v<br>         +------------------------+<br>         |   Connection Handler   |<br>         |  (parses, dispatches)  |<br>         +-----------+------------+<br>                     |<br>           [CPU-bound task added]<br>                     |<br>          +----------v----------+<br>          |     Thread Pool     |<br>          |  (4-16+ worker threads)<br>          +----------+----------+<br>                     |<br>        [Process, compute, respond]<br>                     |<br>          +----------v----------+<br>          |     Send Response   |<br>          +---------------------+</pre><h3>⚠️ What Not to Do for Scale</h3><pre>| Anti-pattern              | Why it&#39;s not scalable                                      |<br>| ------------------------- | ---------------------------------------------------------- |<br>| One thread per connection | Threads consume memory and CPU; won’t scale beyond \~1k-2k |<br>| Blocking sockets          | Threads block on reads/writes, reducing throughput         |<br>| Forking per request       | Slow and memory-heavy, used in old CGI-based systems       |</pre><h3>🧩 When to Consider Proactor Instead</h3><ul><li>On <strong>Windows</strong>, where IOCP (I/O Completion Ports) give true Proactor behavior.</li><li>If you’re using <strong>Boost.Asio</strong>, which abstracts both Reactor (Linux) and Proactor (Windows).</li></ul><p>Boost.Asio handles scalability well under both patterns depending on the OS.</p><h3>🔧 Toolkits That Scale Well</h3><pre>| Library        | Pattern Used            | Notes                                      |<br>| -------------- | ----------------------- | ------------------------------------------ |<br>| **libuv**      | Reactor                 | Used in Node.js                            |<br>| **libevent**   | Reactor                 | Lightweight, C-based                       |<br>| **Boost.Asio** | Reactor/Proactor hybrid | Very flexible, modern C++                  |<br>| **Seastar**    | Shared-nothing async    | Ultra-scalable, lockless, used by ScyllaDB |<br>| **gRPC**       | Proactor + Thread Pool  | Built on top of `libuv`/`epoll`/`IOCP`     |</pre><h3>✅ Final Recommendation</h3><h4><em>For </em><strong><em>cross-platform</em></strong><em> and </em><strong><em>high-performance TCP servers</em></strong><em>, use:</em></h4><h3>🏆 Reactor + Thread Pool + Non-blocking I/O</h3><h4><em>It’s the most </em><strong><em>scalable, efficient, and battle-tested</em></strong><em> combo in C++ on Linux.</em></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8130e72f57fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two pointer technique implementation]]></title>
            <link>https://medium.com/@abhishek.kr121/two-pointer-technique-implementation-c4fc44ae5aa7?source=rss-e3ded9bf3de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4fc44ae5aa7</guid>
            <category><![CDATA[two-pointer-technique]]></category>
            <dc:creator><![CDATA[Abhishek Kr]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 03:35:16 GMT</pubDate>
            <atom:updated>2024-12-07T06:46:06.182Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Q.1</strong> 3Sum<br>Problem: Find all unique triplets in an array that sum up to zero using a two-pointer technique.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;algorithm&gt;<br><br>std::vector&lt;std::vector&lt;int&gt;&gt; threeSum(std::vector&lt;int&gt;&amp; nums) {<br>    std::vector&lt;std::vector&lt;int&gt;&gt; result;<br>    std::sort(nums.begin(), nums.end()); // Step 1: Sort the array<br><br>    for (size_t i = 0; i &lt; nums.size(); ++i) {<br>        // Skip duplicate values for the first element<br>        if (i &gt; 0 &amp;&amp; nums[i] == nums[i - 1]) {<br>            continue;<br>        }<br><br>        int target = -nums[i];<br>        size_t left = i + 1;<br>        size_t right = nums.size() - 1;<br><br>        while (left &lt; right) {<br>            int sum = nums[left] + nums[right];<br>            if (sum == target) {<br>                result.push_back({nums[i], nums[left], nums[right]});<br>                <br>                // Skip duplicates for the second and third elements<br>                while (left &lt; right &amp;&amp; nums[left] == nums[left + 1]) {<br>                    ++left;<br>                }<br>                while (left &lt; right &amp;&amp; nums[right] == nums[right - 1]) {<br>                    --right;<br>                }<br><br>                ++left;<br>                --right;<br>            } else if (sum &lt; target) {<br>                ++left; // Increase the sum<br>            } else {<br>                --right; // Decrease the sum<br>            }<br>        }<br>    }<br><br>    return result;<br>}<br><br>int main() {<br>    std::vector&lt;int&gt; nums = {-1, 0, 1, 2, -1, -4};<br>    std::vector&lt;std::vector&lt;int&gt;&gt; result = threeSum(nums);<br><br>    std::cout &lt;&lt; &quot;Unique triplets that sum to zero:\n&quot;;<br>    for (const auto&amp; triplet : result) {<br>        std::cout &lt;&lt; &quot;[&quot; &lt;&lt; triplet[0] &lt;&lt; &quot;, &quot; &lt;&lt; triplet[1] &lt;&lt; &quot;, &quot; &lt;&lt; triplet[2] &lt;&lt; &quot;]\n&quot;;<br>    }<br><br>    return 0;<br>}</pre><p><strong>Q.2</strong> 3Sum Closest<br>Problem: Find a triplet that is closest to a given target using a two-pointer technique.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;algorithm&gt;<br>#include &lt;cmath&gt; // For std::abs<br><br>int threeSumClosest(std::vector&lt;int&gt;&amp; nums, int target) {<br>    std::sort(nums.begin(), nums.end()); // Step 1: Sort the array<br>    int closestSum = nums[0] + nums[1] + nums[2]; // Initialize with the first triplet<br><br>    for (size_t i = 0; i &lt; nums.size() - 2; ++i) {<br>        size_t left = i + 1;<br>        size_t right = nums.size() - 1;<br><br>        while (left &lt; right) {<br>            int currentSum = nums[i] + nums[left] + nums[right];<br><br>            // Update closestSum if currentSum is closer to the target<br>            if (std::abs(target - currentSum) &lt; std::abs(target - closestSum)) {<br>                closestSum = currentSum;<br>            }<br><br>            // Adjust pointers based on the sum<br>            if (currentSum &lt; target) {<br>                ++left; // Increase the sum<br>            } else if (currentSum &gt; target) {<br>                --right; // Decrease the sum<br>            } else {<br>                // If currentSum == target, it&#39;s the closest possible<br>                return currentSum;<br>            }<br>        }<br>    }<br><br>    return closestSum;<br>}<br><br>int main() {<br>    std::vector&lt;int&gt; nums = {-1, 2, 1, -4};<br>    int target = 1;<br><br>    int result = threeSumClosest(nums, target);<br>    std::cout &lt;&lt; &quot;The closest sum to &quot; &lt;&lt; target &lt;&lt; &quot; is: &quot; &lt;&lt; result &lt;&lt; std::endl;<br><br>    return 0;<br>}</pre><p>Q3. Sort Colors Problem: Sort an array of colors using a two-pointer technique.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br><br>void sortColors(std::vector&lt;int&gt;&amp; nums) {<br>    int low = 0, mid = 0, high = nums.size() - 1;<br><br>    while (mid &lt;= high) {<br>        if (nums[mid] == 0) {<br>            std::swap(nums[low], nums[mid]);<br>            ++low;<br>            ++mid;<br>        } else if (nums[mid] == 1) {<br>            ++mid;<br>        } else { // nums[mid] == 2<br>            std::swap(nums[mid], nums[high]);<br>            --high;<br>        }<br>    }<br>}<br><br>int main() {<br>    std::vector&lt;int&gt; nums = {2, 0, 2, 1, 1, 0};<br>    sortColors(nums);<br><br>    std::cout &lt;&lt; &quot;Sorted colors: &quot;;<br>    for (int num : nums) {<br>        std::cout &lt;&lt; num &lt;&lt; &quot; &quot;;<br>    }<br><br>    return 0;<br>}</pre><p>Q4. Remove nth node from a linklist.</p><pre>#include &lt;iostream&gt;<br><br>struct ListNode {<br>    int val;<br>    ListNode* next;<br>    ListNode() : val(0), next(nullptr) {}<br>    ListNode(int x) : val(x), next(nullptr) {}<br>    ListNode(int x, ListNode* next) : val(x), next(next) {}<br>};<br><br>class Solution {<br>public:<br>    ListNode* removeNthFromEnd(ListNode* head, int n) {<br>        ListNode dummy(0, head); // Dummy node to handle edge cases<br>        ListNode* first = &amp;dummy;<br>        ListNode* second = &amp;dummy;<br><br>        // Move first pointer n+1 steps ahead<br>        for (int i = 0; i &lt;= n; ++i) {<br>            first = first-&gt;next;<br>        }<br><br>        // Move both pointers until first reaches the end<br>        while (first != nullptr) {<br>            first = first-&gt;next;<br>            second = second-&gt;next;<br>        }<br><br>        // Remove the nth node<br>        second-&gt;next = second-&gt;next-&gt;next;<br><br>        return dummy.next; // Return the new head<br>    }<br>};<br><br>// Helper function to print the linked list<br>void printList(ListNode* head) {<br>    while (head) {<br>        std::cout &lt;&lt; head-&gt;val &lt;&lt; &quot; &quot;;<br>        head = head-&gt;next;<br>    }<br>    std::cout &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    // Create linked list: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5<br>    ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));<br><br>    Solution solution;<br>    int n = 2; // Remove 2nd node from the end<br>    head = solution.removeNthFromEnd(head, n);<br><br>    std::cout &lt;&lt; &quot;Updated Linked List: &quot;;<br>    printList(head);<br><br>    return 0;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4fc44ae5aa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variadic Templates in C++]]></title>
            <link>https://medium.com/@abhishek.kr121/variadic-templates-in-c-6955933f5781?source=rss-e3ded9bf3de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6955933f5781</guid>
            <dc:creator><![CDATA[Abhishek Kr]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 09:40:50 GMT</pubDate>
            <atom:updated>2026-09-04T04:15:26.059Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Variadic templates</strong> in C++ allow you to write templates that can accept an arbitrary number of template arguments. This feature was introduced in <strong>C++11</strong> and is useful for creating flexible, type-safe functions and classes.</p><h3>Key Syntax</h3><p>A variadic template uses:</p><ol><li><strong>Template parameter pack</strong>: Denoted by typename... Args (or class... Args).</li><li><strong>Function parameter pack</strong>: Denoted by Args... args.</li></ol><pre>template &lt;typename... Args&gt;<br>void func(Args... args) {<br>    // Implementation<br>}</pre><ul><li>Args... is the <strong>template parameter pack</strong> that can accept zero or more types.</li><li>args... is the <strong>function parameter pack</strong>, corresponding to the Args types.</li></ul><h3>Basic Example</h3><h4>Printing Arbitrary Arguments</h4><pre>#include &lt;iostream&gt;<br><br>// Variadic template function<br>template &lt;typename... Args&gt;<br>void print(Args... args) {<br>    // Use fold expression (C++17) to unpack arguments and print<br>    ((std::cout &lt;&lt; args &lt;&lt; &quot; &quot;), ...) &lt;&lt; std::endl;<br>}<br><br>int main() {<br>    print(1, 2.5, &quot;hello&quot;, &#39;c&#39;); // Output: 1 2.5 hello c <br>    return 0;<br>}</pre><h3>Recursion with Variadic Templates</h3><p>Before C++17 (without fold expressions), variadic templates were often implemented using recursion.</p><h4>Example: Printing Arguments (C++11)</h4><pre>#include &lt;iostream&gt;<br><br>// Base case: No arguments<br>void print() {<br>    std::cout &lt;&lt; std::endl;<br>}<br><br>// Recursive variadic template<br>template &lt;typename T, typename... Args&gt;<br>void print(T first, Args... rest) {<br>    std::cout &lt;&lt; first &lt;&lt; &quot; &quot;; // Process the first argument<br>    print(rest...);            // Recursively call with the remaining arguments<br>}<br><br>int main() {<br>    print(1, 2.5, &quot;hello&quot;, &#39;c&#39;); // Output: 1 2.5 hello c<br>    return 0;<br>}</pre><h3>Parameter Pack Expansion</h3><p>Parameter packs (Args...) can be expanded in several contexts:</p><p><strong>Function calls</strong>:</p><pre>template &lt;typename... Args&gt;<br>void callFunction(void (*func)(Args...), Args... args) {<br>    func(args...); // Unpacks args... and passes them to func<br>}</pre><p><strong>Initializer lists</strong>:</p><pre>template &lt;typename... Args&gt;<br>void print(Args... args) {<br>    std::initializer_list&lt;int&gt;{(std::cout &lt;&lt; args &lt;&lt; &quot; &quot;, 0)...};<br>    std::cout &lt;&lt; std::endl;<br>}</pre><p><strong>Class templates</strong>:</p><pre>template &lt;typename... Args&gt;<br>class MyClass {};<br>MyClass&lt;int, double, std::string&gt; obj; // Instantiated with 3 types</pre><h3>Fold Expressions (C++17)</h3><p>Fold expressions simplify handling variadic templates by applying an operator across all elements in a parameter pack.</p><h4>Syntax:</h4><ul><li><strong>Unary folds</strong>:</li><li>(... op args) – Left fold.</li><li>(args op ...) – Right fold.</li><li><strong>Binary folds</strong>:</li><li>(init op ... op args) – Left fold with initial value.</li><li>(args op ... op init) – Right fold with initial value.</li></ul><h4>Example: Summing Arguments</h4><pre>#include &lt;iostream&gt;<br><br>template &lt;typename... Args&gt;<br>auto sum(Args... args) {<br>    return (args + ...); // Fold expression (Left fold)<br>}<br><br>int main() {<br>    std::cout &lt;&lt; sum(1, 2, 3, 4) &lt;&lt; std::endl; // Output: 10<br>    return 0;<br>}</pre><h3>Using Variadic Templates in Classes</h3><h4>Example: Tuple Implementation</h4><pre>#include &lt;iostream&gt;<br>#include &lt;tuple&gt;<br><br>// Class template with variadic arguments<br>template &lt;typename... Args&gt;<br>class MyTuple {<br>public:<br>    std::tuple&lt;Args...&gt; data;<br><br>    MyTuple(Args... args) : data(args...) {}<br><br>    void print() {<br>        std::apply([](auto&amp;&amp;... args) { ((std::cout &lt;&lt; args &lt;&lt; &quot; &quot;), ...); }, data);<br>        std::cout &lt;&lt; std::endl;<br>    }<br>};<br><br>int main() {<br>    MyTuple&lt;int, double, std::string&gt; myTuple(1, 2.5, &quot;hello&quot;);<br>    myTuple.print(); // Output: 1 2.5 hello<br>    return 0;<br>}</pre><h3>Common Use Cases</h3><ol><li><strong>Generic Functions</strong>:</li></ol><ul><li>Logging, printing, or summing arbitrary arguments.</li></ul><p><strong>2. Forwarding Arguments</strong>:</p><p>Perfect forwarding of arguments to other functions.</p><p><strong>3. Template Metaprogramming</strong>:</p><ul><li>Creating generic data structures or algorithms.</li></ul><p><strong>4. Flexible Constructors</strong>:</p><ul><li>Initializing classes with arbitrary parameters.</li></ul><h3>Advantages of Variadic Templates</h3><ul><li>Flexibility: Handle multiple types and arbitrary numbers of arguments.</li><li>Type Safety: Enforced by the compiler at compile time.</li><li>Efficiency: No need to manually handle argument packing/unpacking.</li></ul><h3>Summary</h3><p>Variadic templates are a powerful feature for writing generic, flexible, and type-safe code. With features like parameter pack expansion, fold expressions, and recursive unpacking, you can handle variable-length template arguments effectively. They are widely used in libraries like std::tuple, std::function, and others.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6955933f5781" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[std::unique_ptr and std::shared_ptr]]></title>
            <link>https://medium.com/@abhishek.kr121/std-unique-ptr-and-std-shared-ptr-3786f97b889a?source=rss-e3ded9bf3de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3786f97b889a</guid>
            <dc:creator><![CDATA[Abhishek Kr]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 02:23:29 GMT</pubDate>
            <atom:updated>2024-12-06T02:23:29.555Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. std::unique_ptr</h3><p>A std::unique_ptr is a smart pointer that owns and manages a resource exclusively. It ensures that the resource is deleted when the unique_ptr goes out of scope.</p><h4>Key Features:</h4><ul><li>Ownership is exclusive; only one unique_ptr can own a resource.</li><li>It is non-copyable but <strong>movable</strong>.</li></ul><h4>Important Functions of std::unique_ptr</h4><p><strong>1. get()</strong></p><ul><li>Returns a raw pointer to the managed object without releasing ownership.</li><li>Use this with caution as it breaks the exclusive ownership semantics.</li></ul><pre>std::unique_ptr&lt;int&gt; ptr = std::make_unique&lt;int&gt;(10);<br>int* raw_ptr = ptr.get(); // Raw pointer to the managed object<br>std::cout &lt;&lt; *raw_ptr &lt;&lt; &quot;\n&quot;; // Output: 10</pre><p><strong>2. release()</strong></p><ul><li>Releases ownership of the managed object and returns the raw pointer. The caller is responsible for deleting the resource.</li></ul><pre>std::unique_ptr&lt;int&gt; ptr = std::make_unique&lt;int&gt;(10);<br>int* raw_ptr = ptr.release(); // Releases ownership<br>delete raw_ptr; // Manually delete the resource3. reset()</pre><ul><li>Deletes the currently managed object and optionally replaces it with a new one.</li><li>Passing nullptr resets the unique_ptr to an empty state.</li></ul><p><strong>3. reset()</strong></p><ul><li>Deletes the currently managed object and optionally replaces it with a new one.</li><li>Passing nullptr resets the unique_ptr to an empty state.</li></ul><pre>std::unique_ptr&lt;int&gt; ptr = std::make_unique&lt;int&gt;(10);<br>ptr.reset(new int(20)); // Deletes the old resource and manages a new one<br>ptr.reset(); // Deletes the managed object and sets the pointer to null</pre><p><strong>4. swap()</strong></p><ul><li>Exchanges the managed object with another unique_ptr.</li></ul><pre>std::unique_ptr&lt;int&gt; ptr1 = std::make_unique&lt;int&gt;(10);<br>std::unique_ptr&lt;int&gt; ptr2 = std::make_unique&lt;int&gt;(20);<br>ptr1.swap(ptr2); // ptr1 now manages 20, ptr2 manages 10</pre><p><strong>5. operator* and </strong><strong>operator-&gt;</strong></p><ul><li>Access the managed object</li></ul><pre>std::unique_ptr&lt;int&gt; ptr = std::make_unique&lt;int&gt;(10);<br>std::cout &lt;&lt; *ptr &lt;&lt; &quot;\n&quot;; // Output: 10</pre><p><strong>6. std::make_unique (C++14)</strong></p><ul><li>Creates a unique_ptr in a single, exception-safe step.</li></ul><pre>auto ptr = std::make_unique&lt;int&gt;(10); // Preferred over manual `new`</pre><h3>2. std::shared_ptr</h3><p>A std::shared_ptr is a smart pointer that shares ownership of a resource. The resource is destroyed when the last shared_ptr owning it is destroyed or reset.</p><h4>Key Features:</h4><ul><li>Reference counting is used to track ownership.</li><li>Multiple shared_ptr instances can share ownership of the same resource.</li></ul><h4>Important Functions of std::shared_ptr</h4><ol><li><strong>use_count()</strong></li></ol><ul><li>Returns the number of shared_ptr instances sharing ownership of the managed object.</li></ul><pre>auto ptr1 = std::make_shared&lt;int&gt;(10);<br>auto ptr2 = ptr1; // Shared ownership<br>std::cout &lt;&lt; ptr1.use_count() &lt;&lt; &quot;\n&quot;; // Output: 2</pre><p><strong>2. get()</strong></p><ul><li>Returns a raw pointer to the managed object without releasing ownership.</li></ul><pre>auto ptr = std::make_shared&lt;int&gt;(10);<br>int* raw_ptr = ptr.get(); // Raw pointer</pre><p><strong>3. reset()</strong></p><ul><li>Releases ownership of the managed object. If the shared_ptr is the last owner, the object is deleted.</li></ul><pre>auto ptr = std::make_shared&lt;int&gt;(10);<br>ptr.reset(); // Deletes the managed object if this is the last owner</pre><p><strong>4. swap()</strong></p><ul><li>Exchanges the managed object with another shared_ptr.</li></ul><pre>auto ptr1 = std::make_shared&lt;int&gt;(10);<br>auto ptr2 = std::make_shared&lt;int&gt;(20);<br>ptr1.swap(ptr2); // ptr1 now manages 20, ptr2 manages 10</pre><p><strong>5. operator* and </strong><strong>operator-&gt;</strong></p><ul><li>Access the managed object</li></ul><p><strong>6. std::make_shared</strong></p><ul><li>Creates a shared_ptr in a single, exception-safe step. It is more efficient than using new because it allocates memory for both the object and control block in one step.</li></ul><pre>auto ptr = std::make_shared&lt;int&gt;(10); // Preferred over manual `new`</pre><h3>When to Use</h3><ul><li><strong>std::unique_ptr</strong>:</li><li>Use when there is a clear single owner of the resource.</li><li>Example: Managing dynamic memory or a resource in RAII fashion.</li><li><strong>std::shared_ptr</strong>:</li><li>Use when multiple objects share ownership of the resource.</li><li>Example: Shared data structures or resources in a multi-threaded environment.</li></ul><p><strong>Using </strong>unique_ptr:</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>void uniquePtrExample() {<br>    auto ptr = std::make_unique&lt;int&gt;(10);<br>    std::cout &lt;&lt; &quot;Value: &quot; &lt;&lt; *ptr &lt;&lt; &quot;\n&quot;;<br><br>    auto ptr2 = std::move(ptr); // Ownership transferred<br>    if (!ptr) {<br>        std::cout &lt;&lt; &quot;ptr is now null\n&quot;;<br>    }<br>}</pre><p><strong>Using </strong>shared_ptr:</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>void sharedPtrExample() {<br>    auto ptr1 = std::make_shared&lt;int&gt;(10);<br>    auto ptr2 = ptr1; // Shared ownership<br><br>    std::cout &lt;&lt; &quot;Use count: &quot; &lt;&lt; ptr1.use_count() &lt;&lt; &quot;\n&quot;; // Output: 2<br><br>    ptr1.reset(); // Releases ptr1&#39;s ownership<br>    std::cout &lt;&lt; &quot;Use count after reset: &quot; &lt;&lt; ptr2.use_count() &lt;&lt; &quot;\n&quot;; // Output: 1<br>}</pre><p>Comparison of unique_ptr and shared_ptr</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*HujRo4ERQkFbTxmlYfkP6Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3786f97b889a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[std::weak_ptr in C++]]></title>
            <link>https://medium.com/@abhishek.kr121/std-weak-ptr-in-c-fb1370b4791e?source=rss-e3ded9bf3de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb1370b4791e</guid>
            <dc:creator><![CDATA[Abhishek Kr]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 02:06:53 GMT</pubDate>
            <atom:updated>2024-12-06T02:06:53.879Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>std::weak_ptr</strong> is a smart pointer that holds a non-owning (weak) reference to an object managed by a std::shared_ptr. It is primarily used to break cyclic references, which can lead to memory leaks in std::shared_ptr.</p><h3>Key Features of std::weak_ptr</h3><ol><li><strong>Non-Owning Reference</strong>:</li></ol><ul><li>A weak_ptr does not affect the reference count of a shared_ptr.</li></ul><p><strong>2. Breaking Cyclic References</strong>:</p><ul><li>It is often used in scenarios where two or more objects hold shared references to each other, causing a cyclic dependency.</li></ul><p><strong>3. Accessing the Object</strong>:</p><ul><li>To access the object managed by a weak_ptr, you must convert it to a std::shared_ptr using lock(). This ensures the object is still valid before accessing it.</li></ul><h3>Example: Breaking Cyclic References</h3><h4>Problem: Cyclic Dependency</h4><p>Two objects reference each other using shared_ptr. This creates a reference cycle, preventing the objects from being destroyed.</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>class B; // Forward declaration<br><br>class A {<br>public:<br>    std::shared_ptr&lt;B&gt; b_ptr; // Shared ownership of B<br>    ~A() { std::cout &lt;&lt; &quot;A destroyed\n&quot;; }<br>};<br><br>class B {<br>public:<br>    std::shared_ptr&lt;A&gt; a_ptr; // Shared ownership of A (causes cyclic dependency)<br>    ~B() { std::cout &lt;&lt; &quot;B destroyed\n&quot;; }<br>};<br><br>int main() {<br>    {<br>        auto a = std::make_shared&lt;A&gt;();<br>        auto b = std::make_shared&lt;B&gt;();<br>        a-&gt;b_ptr = b;<br>        b-&gt;a_ptr = a; // Cyclic dependency<br><br>        // Both a and b are destroyed when leaving the scope, right? No!<br>    }<br>    std::cout &lt;&lt; &quot;Exiting main\n&quot;; // A and B are never destroyed!<br>    return 0;<br>}</pre><h4>Output (with Memory Leak):</h4><pre>Exiting main</pre><p>The objects are not destroyed because of the cyclic dependency: a and b hold shared references to each other, so their reference counts never reach zero.</p><h4>Solution: Use std::weak_ptr</h4><p>Replace one of the shared_ptr with a weak_ptr to break the cycle.</p><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>class B; // Forward declaration<br><br>class A {<br>public:<br>    std::weak_ptr&lt;B&gt; b_ptr; // Weak ownership of B<br>    ~A() { std::cout &lt;&lt; &quot;A destroyed\n&quot;; }<br>};<br><br>class B {<br>public:<br>    std::shared_ptr&lt;A&gt; a_ptr; // Shared ownership of A<br>    ~B() { std::cout &lt;&lt; &quot;B destroyed\n&quot;; }<br>};<br><br>int main() {<br>    {<br>        auto a = std::make_shared&lt;A&gt;();<br>        auto b = std::make_shared&lt;B&gt;();<br>        a-&gt;b_ptr = b; // Weak reference<br>        b-&gt;a_ptr = a; // Shared reference<br>    }<br>    std::cout &lt;&lt; &quot;Exiting main\n&quot;; // Now, A and B are destroyed!<br>    return 0;<br>}</pre><p>Output:</p><pre>A destroyed<br>B destroyed<br>Exiting main</pre><h3>Explanation of Key Functions</h3><ol><li><strong>Creating a Weak Pointer</strong>:</li></ol><ul><li>You can assign a std::shared_ptr to a std::weak_ptr.</li><li>A std::weak_ptr does not increment the reference count of the std::shared_ptr.</li></ul><pre>std::shared_ptr&lt;int&gt; shared = std::make_shared&lt;int&gt;(42);<br>std::weak_ptr&lt;int&gt; weak = shared; // Weak reference to the shared pointer</pre><p><strong>2. Accessing the Managed Object</strong>:</p><ul><li>Use lock() to create a temporary std::shared_ptr if the object is still valid.</li><li>Always check if the weak_ptr is valid before dereferencing.</li></ul><pre>if (auto sp = weak.lock()) { // Create a shared_ptr if the object is still valid<br>    std::cout &lt;&lt; &quot;Value: &quot; &lt;&lt; *sp &lt;&lt; &quot;\n&quot;;<br>} else {<br>    std::cout &lt;&lt; &quot;The object has been destroyed.\n&quot;;<br>}</pre><p><strong>3. Checking Validity</strong>:</p><ul><li>Use expired() to check if the weak_ptr is pointing to a valid object.</li></ul><pre>if (weak.expired()) {<br>    std::cout &lt;&lt; &quot;The object is no longer valid.\n&quot;;<br>}</pre><h3>Advantages of std::weak_ptr</h3><ol><li>Prevents memory leaks caused by cyclic dependencies.</li><li>Provides a way to observe an object managed by a shared_ptr without extending its lifetime.</li><li>Lightweight and efficient as it does not affect the reference count.</li></ol><p>Use std::weak_ptr when you need to reference an object without claiming ownership, especially in cyclic dependency scenarios.</p><h3><strong>How to check valadity before dereferncing weak_prt?</strong></h3><h3>1. Using lock() Method</h3><ul><li>The lock() method creates a std::shared_ptr from a std::weak_ptr if the object it points to is still valid.</li><li>If the object has been destroyed, lock() returns an empty std::shared_ptr</li></ul><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>int main() {<br>    std::shared_ptr&lt;int&gt; shared = std::make_shared&lt;int&gt;(42);<br>    std::weak_ptr&lt;int&gt; weak = shared;<br><br>    // Check if the weak_ptr is valid<br>    if (auto sp = weak.lock()) { // sp is a shared_ptr<br>        std::cout &lt;&lt; &quot;Value: &quot; &lt;&lt; *sp &lt;&lt; &quot;\n&quot;; // Dereferencing shared_ptr<br>    } else {<br>        std::cout &lt;&lt; &quot;The object has been destroyed.\n&quot;;<br>    }<br><br>    // Reset the shared_ptr to simulate object destruction<br>    shared.reset();<br><br>    // Check validity again<br>    if (auto sp = weak.lock()) {<br>        std::cout &lt;&lt; &quot;Value: &quot; &lt;&lt; *sp &lt;&lt; &quot;\n&quot;;<br>    } else {<br>        std::cout &lt;&lt; &quot;The object has been destroyed.\n&quot;;<br>    }<br><br>    return 0;<br>}</pre><pre>Value: 42<br>The object has been destroyed.</pre><h3>2. Using expired() Method</h3><ul><li>The expired() method returns true if the object managed by the std::weak_ptr has been destroyed.</li><li>It is useful for a quick validity check but does not give direct access to the object.</li></ul><pre>#include &lt;iostream&gt;<br>#include &lt;memory&gt;<br><br>int main() {<br>    std::shared_ptr&lt;int&gt; shared = std::make_shared&lt;int&gt;(42);<br>    std::weak_ptr&lt;int&gt; weak = shared;<br><br>    if (!weak.expired()) {<br>        std::cout &lt;&lt; &quot;Weak pointer is valid.\n&quot;;<br>    } else {<br>        std::cout &lt;&lt; &quot;Weak pointer is invalid.\n&quot;;<br>    }<br><br>    // Reset the shared_ptr to simulate object destruction<br>    shared.reset();<br><br>    if (!weak.expired()) {<br>        std::cout &lt;&lt; &quot;Weak pointer is valid.\n&quot;;<br>    } else {<br>        std::cout &lt;&lt; &quot;Weak pointer is invalid.\n&quot;;<br>    }<br><br>    return 0;<br>}</pre><pre>Weak pointer is valid.<br>Weak pointer is invalid.</pre><h3>Preferred Approach: Use lock()</h3><ul><li>Using lock() is the safer approach because it gives you a std::shared_ptr that guarantees the object is still valid while you access it.</li><li>If you use expired() and then try to access the object without locking, the object might have been destroyed in between the check and access (especially in multi-threaded programs).</li></ul><h3>Best Practice:</h3><p>Always use lock() when accessing the object to avoid potential dangling pointer issues:</p><pre>if (auto sp = weak.lock()) {<br>    // Safe to access *sp<br>} else {<br>    // Object no longer exists<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb1370b4791e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rate limiting Algorithms]]></title>
            <link>https://medium.com/@abhishek.kr121/rate-limiting-algorithms-77c3f11485bd?source=rss-e3ded9bf3de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/77c3f11485bd</guid>
            <category><![CDATA[rate-limiting-algorithms]]></category>
            <dc:creator><![CDATA[Abhishek Kr]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 11:38:03 GMT</pubDate>
            <atom:updated>2024-12-02T11:38:03.110Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rate limiting Algorithm</h3><p><strong>Rate limiting algorithms</strong> are techniques used to control the rate of requests or operations in systems like APIs, servers, or distributed systems. These algorithms help enforce policies like preventing abuse, managing resource usage, and maintaining system stability. Below are some commonly used rate-limiting algorithms:</p><h3>1. Token Bucket</h3><p><strong>Description</strong>:</p><ul><li>Maintains a “bucket” that holds tokens. Each request consumes one token.</li><li>Tokens are added to the bucket at a fixed rate up to a maximum capacity.</li></ul><p><strong>Key Characteristics</strong>:</p><ul><li>Allows for bursts of activity as long as tokens are available.</li><li>Smoothly refills tokens at a steady rate.</li></ul><p><strong>Steps</strong>:</p><ol><li>Tokens are added at a rate of rrr tokens per second.</li><li>If the bucket is full, additional tokens are discarded.</li><li>A request is allowed only if there is at least one token available; otherwise, it is rejected or delayed.</li></ol><p><strong>Use Case</strong>:</p><ul><li>APIs that need to allow bursts of requests but limit the overall rate.</li></ul><h3>2. Leaky Bucket</h3><p><strong>Description</strong>:</p><ul><li>Treats requests as drops added to a bucket. Drops leak out of the bucket at a constant rate.</li><li>If the bucket overflows, incoming requests are discarded.</li></ul><p><strong>Key Characteristics</strong>:</p><ul><li>Ensures a steady outflow rate.</li><li>Smooths out spikes in traffic.</li></ul><p><strong>Steps</strong>:</p><ol><li>Requests enter the bucket as water drops.</li><li>Water leaks out at a fixed rate.</li><li>If the bucket overflows, incoming requests are rejected.</li></ol><p><strong>Use Case</strong>:</p><ul><li>Systems that require a consistent rate of processing.</li></ul><h3>3. Fixed Window Counter</h3><p><strong>Description</strong>:</p><ul><li>Divides time into fixed intervals (windows).</li><li>Counts the number of requests in the current window.</li></ul><p><strong>Key Characteristics</strong>:</p><ul><li>Simple and easy to implement.</li><li>Vulnerable to burst requests at window boundaries (e.g., many requests at the end of one window and the beginning of the next).</li></ul><p><strong>Steps</strong>:</p><ol><li>Maintain a counter for each time window.</li><li>If the counter exceeds the limit, requests are rejected.</li><li>Reset the counter at the start of the next window.</li></ol><p><strong>Use Case</strong>:</p><ul><li>Lightweight rate-limiting for APIs or services.</li></ul><h3>4. Sliding Window Counter</h3><p><strong>Description</strong>:</p><ul><li>Similar to the Fixed Window Counter but uses a sliding time window.</li><li>Partitions time into smaller intervals and keeps a record of requests in each interval.</li></ul><p><strong>Key Characteristics</strong>:</p><ul><li>Reduces burstiness at window boundaries.</li><li>Slightly more complex than Fixed Window Counter.</li></ul><p><strong>Steps</strong>:</p><ol><li>Track request counts in recent intervals (e.g., last 5 seconds).</li><li>Sum the counts within the sliding window.</li><li>Reject requests if the total exceeds the limit.</li></ol><p><strong>Use Case</strong>:</p><ul><li>Real-time traffic shaping where burst control is important.</li></ul><h3>5. Sliding Window Log</h3><p><strong>Description</strong>:</p><ul><li>Maintains a log of timestamps for each request.</li><li>Allows more granular control by precisely tracking individual requests.</li></ul><p><strong>Key Characteristics</strong>:</p><ul><li>Provides accurate rate limiting.</li><li>Requires more memory to store timestamps.</li></ul><p><strong>Steps</strong>:</p><ol><li>Store the timestamp of each incoming request in a list or queue.</li><li>Remove timestamps outside the sliding window.</li><li>Reject a request if the number of timestamps within the window exceeds the limit.</li></ol><p><strong>Use Case</strong>:</p><ul><li>Systems needing precise control of request rates.</li></ul><h3>6. Concurrent Limiting</h3><p><strong>Description</strong>:</p><ul><li>Limits the number of concurrent actions (e.g., API calls or threads).</li></ul><p><strong>Key Characteristics</strong>:</p><ul><li>Controls resource usage in real-time.</li><li>May use semaphores or similar constructs.</li></ul><p><strong>Steps</strong>:</p><ol><li>Maintain a counter of current active operations.</li><li>Increment the counter when a new operation starts and decrement it when it finishes.</li><li>Reject new operations if the counter exceeds the limit.</li></ol><p><strong>Use Case</strong>:</p><ul><li>Controlling simultaneous connections or processing threads.</li></ul><h3>7. Rate Limiting with Queues</h3><p><strong>Description</strong>:</p><ul><li>Uses a queue to buffer requests and processes them at a controlled rate.</li></ul><p><strong>Key Characteristics</strong>:</p><ul><li>Ensures fairness by processing requests in order.</li><li>Adds latency due to queuing.</li></ul><p><strong>Steps</strong>:</p><ol><li>Enqueue incoming requests.</li><li>Process requests from the queue at a fixed rate.</li><li>Reject or delay requests if the queue is full.</li></ol><p><strong>Use Case</strong>:</p><ul><li>Systems requiring fairness and controlled throughput.</li></ul><p><strong>Comparison of Algorithms:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*eE9oSTyM7pMq4D1U4EaUcw.png" /></figure><h3>Choosing the Right Algorithm</h3><p>The choice of algorithm depends on:</p><ul><li><strong>Traffic Patterns</strong>: Are bursts acceptable, or should they be smoothed?</li><li><strong>Accuracy Requirements</strong>: How strict should the rate limiting be?</li><li><strong>System Constraints</strong>: Memory, processing power, and implementation complexity.</li></ul><p>For most API rate-limiting needs, <strong>Token Bucket</strong> or <strong>Sliding Window Counter</strong> are common choices due to their balance of simplicity and effectiveness.</p><p>Time-Wheeler Algorithm:</p><p>The <strong>Time-Wheeler Algorithm</strong> for rate limiting, more formally known as the <strong>Hierarchical Token Bucket Algorithm</strong> or <strong>Time Wheel Rate Limiting</strong>, is a technique used to efficiently implement time-based rate limiting. It is often used in networking and systems where operations or requests need to be regulated over multiple time scales. The algorithm combines the <strong>token bucket</strong> mechanism with a <strong>circular time wheel</strong> for efficient handling of time-sensitive operations.</p><h3>How It Works</h3><ol><li><strong>Circular Time Wheel</strong>:</li></ol><ul><li>Imagine a circular array (time wheel) divided into slots, where each slot represents a fixed time interval (e.g., 1 second or 100ms).</li><li>Requests or events are mapped to a specific slot based on when they occur or should be processed.</li></ul><p><strong>2. Token Bucket Integration</strong>:</p><ul><li>Each slot acts like a mini-token bucket.</li><li>Tokens are replenished at a regular interval, ensuring that requests in each slot adhere to rate-limiting rules.</li></ul><p><strong>3. Efficient Scheduling</strong>:</p><ul><li>As the time progresses, the algorithm iterates over the slots in a circular fashion (like a clock ticking).</li><li>Requests in the current slot are processed, and tokens are checked to ensure rate limits are respected.</li></ul><p><strong>4. Hierarchical Design (Optional)</strong>:</p><ul><li>For systems with complex rate-limiting requirements (e.g., hourly, daily, and monthly limits), multiple time wheels of different granularities can be used.</li><li>The coarse-grained wheels (e.g., hourly) regulate overall limits, while fine-grained wheels (e.g., per second) handle immediate requests.</li></ul><h3>Key Features</h3><ul><li><strong>Granularity</strong>: The resolution of the time wheel determines how finely requests are controlled.</li><li><strong>Circular Nature</strong>: The circular design ensures that memory usage is constant and does not grow over time.</li><li><strong>Multi-Level Control</strong>: Hierarchical time wheels allow enforcement of multiple rate limits (e.g., per second, per minute).</li><li><strong>Efficiency</strong>: Events are grouped into slots, reducing the need to handle individual timestamps.</li></ul><h3>Example Use Case</h3><p><strong>Networking</strong>: A router or firewall might use a Time-Wheeler Algorithm to enforce rate limits on packets per second. The circular array tracks packets in 1-second slots, and tokens ensure the rate does not exceed a predefined threshold.</p><p><strong>API Gateways</strong>: A service might use a hierarchical time wheel to enforce:</p><ul><li><strong>Per-second</strong>: Maximum of 10 requests per second.</li><li><strong>Per-minute</strong>: Maximum of 100 requests per minute.</li><li><strong>Per-hour</strong>: Maximum of 1000 requests per hour.</li></ul><h3>Advantages</h3><p><strong>Low Memory Overhead</strong>:</p><ul><li>Fixed-sized time wheel uses constant memory regardless of the number of requests.</li></ul><p><strong>Efficient</strong>:</p><ul><li>Events are aggregated by slots, reducing the need for complex operations on individual timestamps.</li></ul><p><strong>Scalable</strong>:</p><ul><li>Handles high rates of incoming requests with minimal processing.</li></ul><p><strong>Flexible</strong>:</p><ul><li>Easily extends to multiple granularities for hierarchical rate limits.</li></ul><h3>Disadvantages</h3><ol><li><strong>Resolution Limitations</strong>:</li></ol><ul><li>The granularity of the time wheel determines the precision of rate limiting.</li></ul><p><strong>2. Complexity</strong>:</p><ul><li>Implementing a hierarchical time wheel can be more complex than simpler algorithms like Token Bucket or Fixed Window.</li></ul><p><strong>3. Slot Collisions</strong>:</p><ul><li>Requests mapped to the same slot are grouped, which might introduce slight inaccuracies if fine-grained control is needed.</li></ul><p>Comparison to Other Algorithms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*1fTwuWtUDJxP5cn83HeebQ.png" /></figure><h3>Summary</h3><p>The <strong>Time-Wheeler Algorithm</strong> is an efficient and scalable rate-limiting approach, particularly suitable for high-performance systems with hierarchical or time-sensitive rate-limiting requirements. While it adds some complexity, its efficiency and ability to manage multiple time scales make it a powerful choice for advanced systems like networking equipment, distributed systems, and API rate limiting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77c3f11485bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebRTC]]></title>
            <link>https://medium.com/@abhishek.kr121/webrtc-461dea3b78f7?source=rss-e3ded9bf3de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/461dea3b78f7</guid>
            <category><![CDATA[webrtc]]></category>
            <dc:creator><![CDATA[Abhishek Kr]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 14:01:12 GMT</pubDate>
            <atom:updated>2024-11-27T14:08:43.598Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>WebRTC (Web Real-Time Communication)</strong> is a technology that allows web browsers and mobile applications to directly exchange audio, video, and data without needing a server in the middle to relay the data. It enables real-time communication (like video calls, voice calls, or file sharing) over the internet. It is based on udp protocol.</p><h3>How Does WebRTC Work?</h3><ol><li><strong>Peer-to-Peer Communication</strong>:</li></ol><ul><li>WebRTC establishes a direct connection (peer-to-peer) between two devices (called “peers”) to send and receive data.</li><li>This avoids unnecessary delays caused by routing data through a central server.</li></ul><p><strong>2. Components of WebRTC</strong>:</p><ul><li><strong>Signaling</strong>: A mechanism to establish a connection by exchanging connection information (e.g., IP addresses, port numbers). This often uses servers like WebSockets, but signaling itself is not part of WebRTC.</li><li><strong>ICE (Interactive Connectivity Establishment)</strong>: Finds the best path between the peers (even if they are behind NATs or firewalls).</li><li><strong>STUN/TURN Servers</strong>:</li><li><strong>STUN</strong> helps determine the public IP address of a peer behind a NAT.</li><li><strong>TURN</strong> acts as a relay server if a direct connection cannot be established.</li><li><strong>Media and Data Channels</strong>: WebRTC supports sending audio, video, and arbitrary data.</li></ul><h3>Step-by-Step Process</h3><h4>1. Signaling: Initial Setup</h4><ul><li>Both peers exchange connection information (like IP addresses, media capabilities, etc.) through a signaling server (using WebSocket, HTTP, etc.).</li><li>The signaling phase uses protocols like SDP (Session Description Protocol).</li></ul><h4>2. Peer Discovery and Connection</h4><ul><li>The peers exchange information via signaling to:</li><li>Identify their network setup (e.g., NAT traversal).</li><li>Share details like codecs and encryption methods.</li></ul><h4>3. NAT Traversal</h4><ul><li><strong>NAT</strong>: Network Address Translation often hides devices behind routers, making direct communication challenging.</li><li>WebRTC uses <strong>STUN/TURN servers</strong> to ensure that peers can locate and connect to each other.</li></ul><h4>4. Secure Connection</h4><ul><li>WebRTC uses encryption by default (DTLS for signaling and SRTP for media) to ensure secure communication.</li><li>No one can eavesdrop on the data being transmitted.</li></ul><h4>5. Data Exchange</h4><ul><li>Once connected, peers can exchange:</li><li><strong>Media Streams</strong>: For audio and video calls.</li><li><strong>Data Channels</strong>: For sending files, messages, or arbitrary data.</li></ul><h3>Simplified Example: A Video Call</h3><ol><li><strong>Signaling</strong>:</li></ol><ul><li>Alice and Bob want to call each other.</li><li>They use a signaling server to exchange their information like public IPs and codecs.</li></ul><p><strong>2. Connection Establishment</strong>:</p><ul><li>Using ICE, Alice and Bob determine the best way to connect (directly or via TURN).</li><li>They set up secure media streams.</li></ul><p><strong>3. Real-Time Communication</strong>:</p><ul><li>Alice sends her video/audio data directly to Bob, and Bob sends his to Alice.</li><li>Both can now see and hear each other in real-time.</li></ul><h3>WebRTC Key Features</h3><ol><li><strong>Real-Time Media</strong>:</li></ol><ul><li>Streams audio and video with low latency.</li></ul><p><strong>2. Data Channels</strong>:</p><ul><li>Transfers arbitrary data (e.g., chat messages, files).</li></ul><p><strong>3. Security</strong>:</p><ul><li>End-to-end encrypted by default.</li></ul><p><strong>4. Cross-Platform</strong>:</p><ul><li>Works on browsers (via JavaScript) and native apps.</li></ul><h3>Why Use WebRTC?</h3><ul><li>For real-time communication like video calls, online gaming, live streaming, and P2P file sharing.</li><li>It reduces latency compared to server-based solutions since the data is sent directly between peers.</li></ul><h3>Challenges</h3><ol><li><strong>NAT/Firewall Traversal</strong>:</li></ol><ul><li>Requires STUN/TURN servers to handle complex network setups.</li></ul><p><strong>2. Signaling</strong>:</p><ul><li>WebRTC doesn’t handle signaling; developers must implement it separately.</li></ul><p><strong>3. Browser Compatibility</strong>:</p><ul><li>Different browsers may have slight variations in WebRTC implementation.</li></ul><h3>Conclusion</h3><p>WebRTC is a powerful tool for enabling real-time communication directly between devices. While it requires initial setup (like signaling servers and NAT traversal mechanisms), once the connection is established, it provides a fast, secure, and direct way to exchange data.</p><h3>Key Protocols Used in WebRTC</h3><p>Although WebRTC relies on UDP for its core data transmission, it incorporates several protocols for specific functionalities:</p><ol><li><strong>DTLS (Datagram Transport Layer Security)</strong>:</li></ol><ul><li>Encrypts and secures the data sent over UDP.</li><li>Ensures that WebRTC communication is private and secure.</li></ul><p><strong>2. SRTP (Secure Real-time Transport Protocol)</strong>:</p><ul><li>Used for transporting audio and video securely over UDP.</li><li>Provides encryption, message authentication, and integrity.</li></ul><p><strong>3. SCTP (Stream Control Transmission Protocol)</strong> (for Data Channels):</p><ul><li>While media streams use UDP, WebRTC’s data channels are built on <strong>SCTP over DTLS over UDP</strong>.</li><li>SCTP ensures reliable and ordered delivery of messages, combining benefits of TCP (reliability) and UDP (low latency).</li></ul><p><strong>4. TURN (Traversal Using Relays around NAT)</strong>:</p><ul><li>When direct peer-to-peer communication is not possible (e.g., due to restrictive firewalls), WebRTC uses a TURN server to relay traffic. TURN works over UDP (preferred) or TCP as a fallback.</li></ul><p><strong>4. Fallback to TCP</strong>:</p><ul><li>If UDP fails (e.g., due to network restrictions), WebRTC can fall back to TCP. However, this is less efficient and may result in higher latency.</li></ul><h3>Summary</h3><ul><li><strong>Default Transport</strong>: UDP.</li><li><strong>Security</strong>: Uses DTLS and SRTP to secure communication over UDP.</li><li><strong>Fallback</strong>: Can use TCP if UDP is blocked, but this is less efficient.</li><li><strong>Data Channels</strong>: Built on SCTP over DTLS over UDP.</li></ul><p>By leveraging UDP and its supporting protocols, WebRTC achieves low-latency, secure, and reliable communication for real-time applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=461dea3b78f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Ordering in Distributed System]]></title>
            <link>https://medium.com/@abhishek.kr121/event-ordering-in-distributed-system-e86e4c341503?source=rss-e3ded9bf3de0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e86e4c341503</guid>
            <dc:creator><![CDATA[Abhishek Kr]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 11:07:00 GMT</pubDate>
            <atom:updated>2024-11-27T11:07:00.192Z</atom:updated>
            <content:encoded><![CDATA[<p>Event ordering in distributed systems is crucial to ensure consistency, coordination, and correctness, especially when multiple processes operate independently and communicate asynchronously. Since distributed systems lack a global clock, event ordering is established using logical methods.</p><h3>Types of Event Ordering</h3><ol><li><strong>Causal Ordering</strong>:</li></ol><ul><li>Reflects the cause-and-effect relationships between events.</li><li>For example, if process P1 sends a message to P2, the message send event at P1 causally precedes the message receive event at P2.</li></ul><p><strong>2. Total Ordering</strong>:</p><ul><li>Establishes a global order for all events in the system, even if they are unrelated.</li><li>Ensures that all processes agree on the same order of events.</li></ul><p><strong>3. Partial Ordering</strong>:</p><ul><li>Establishes order only for causally related events.</li><li>Unrelated events remain unordered.</li></ul><h3>Mechanisms for Event Ordering</h3><h4>1. Logical Clocks</h4><p>Logical clocks provide a mechanism to order events without requiring synchronized physical clocks.</p><ul><li><strong>Lamport Timestamps (Partial Order)</strong>:</li><li>Each process maintains a counter that increments with each event.</li><li>Events are ordered by comparing their timestamps:</li><li>If e1 happens before e2: L(e1)&lt;L(e2)).</li><li>Events with the same timestamp can be resolved using process IDs as tiebreakers.</li><li><strong>Rules</strong>:</li><li>e1→e2 (e1 causally precedes e2) if:</li><li>Both events occur in the same process, and e1happens before e2, or</li><li>P1 sends a message m(event e1) to P2, and P2 receives m (event e2).</li><li><strong>Limitations</strong>:</li><li>Lamport Timestamps can establish only a partial order of events; they cannot capture concurrency.</li></ul><h4>2. Vector Clocks (Causal Order)</h4><p>Vector clocks extend Lamport Timestamps to provide causality:</p><ul><li>Each process maintains a vector V[i] of size N(number of processes).</li><li>Each vector element V[i] represents the logical clock for process i.</li></ul><p><strong>Rules</strong>:</p><p><strong>1. Internal Events</strong>:</p><ul><li>Increment V[i][i] for every event in process i.</li></ul><p><strong>2. Message Sending</strong>:</p><ul><li>Attach the sender’s vector V[i] to the message.</li></ul><p><strong>3. Message Receiving</strong>:</p><ul><li>Update the receiver’s vector by taking the element-wise maximum of its vector and the received vector: V[j][k]=max⁡(V[j][k],V[i][k])</li><li>Increment V[j][j].</li></ul><p><strong>Order Comparison</strong>:</p><ul><li>V1&lt;V2 if V1[k]≤V2[k] for all k, and V1[j]&lt;V2[j] for at least one j.</li><li>Otherwise, the events are <strong>concurrent</strong>.</li></ul><h4>3. Total Ordering with Logical Clocks</h4><p>To achieve a total order (all events are comparable):</p><ul><li><strong>Lamport Clocks with Tiebreakers</strong>:</li><li>Events are ordered first by timestamp. If timestamps are the same, use process IDs to break ties.</li><li><strong>Global Logical Sequence Number</strong>:</li><li>A central coordinator assigns sequence numbers to events as they occur.</li></ul><h3>Applications of Event Ordering</h3><ol><li><strong>Distributed Mutual Exclusion</strong>:</li></ol><ul><li>Algorithms like Ricart-Agrawala and Suzuki-Kasami use event ordering to ensure fair access to critical sections.</li></ul><p><strong>2. Causal Multicast</strong></p><ul><li>Ensures that messages are delivered in the order of their causal dependencies.</li></ul><p><strong>3. Distributed Debugging</strong>:</p><ul><li>Helps identify the causal relationships between events during debugging.</li></ul><p><strong>4. Replication and Consistency</strong>:</p><ul><li>In distributed databases, event ordering ensures that all replicas apply updates in the same order.</li></ul><p><strong>5. Snapshot Algorithms</strong>:</p><ul><li>Algorithms like Chandy-Lamport use event ordering to capture a consistent global state of the system.</li></ul><h3>Example</h3><p>Consider three processes P1, P2, P3, and the following events:</p><ol><li>P1 sends message M to P2.</li><li>P2 receives M.</li><li>P3 performs an independent event.</li></ol><p><strong>Using Lamport Timestamps</strong>:</p><ul><li>P1: Send M: L(P1)=1.</li><li>P2 : Receive M: L(P2)=2 (based on L(P1).</li><li>P3: Independent event: L(P3)=1.</li></ul><p><strong>Using Vector Clocks</strong>:</p><ul><li>P1: Send MMM: V(P1)=[1,0,0].</li><li>P2: Receive MMM: V(P2)=[1,1,0] (merge vectors and increment local clock).</li><li>P3: Independent event: V(P3)=[0,0,1].</li></ul><h3>Conclusion</h3><p>Event ordering in distributed systems ensures that processes agree on the sequence of events despite the absence of a global clock. Techniques like Lamport Timestamps and Vector Clocks provide partial or causal order, while extensions can achieve total order when required for specific applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e86e4c341503" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>