<?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 Oleh Slabak on Medium]]></title>
        <description><![CDATA[Stories by Oleh Slabak on Medium]]></description>
        <link>https://medium.com/@olehslabak?source=rss-850fc6e62b2c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oI95sDhtVqNJzC27vmixOA.jpeg</url>
            <title>Stories by Oleh Slabak on Medium</title>
            <link>https://medium.com/@olehslabak?source=rss-850fc6e62b2c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:07:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olehslabak/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[C++ home work : Function]]></title>
            <link>https://olehslabak.medium.com/c-home-work-function-86c6aba81f73?source=rss-850fc6e62b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/86c6aba81f73</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[function]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Oleh Slabak]]></dc:creator>
            <pubDate>Tue, 10 Mar 2026 08:32:39 GMT</pubDate>
            <atom:updated>2026-03-10T08:32:39.174Z</atom:updated>
            <content:encoded><![CDATA[<p>The C++ class template std::function is a <strong>general-purpose polymorphic function wrapper</strong> that can store, copy, and invoke any <em>callable</em> target, such as functions, lambda expressions, function objects, and pointers to member functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oCGJsAr4COxKPQdd" /><figcaption>Photo by <a href="https://unsplash.com/@rooney?utm_source=medium&amp;utm_medium=referral">Taylor Rooney</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Requirements</h3><ul><li>Implement a simplified <strong>std::function-like wrapper</strong> using <strong>type erasure</strong>.</li><li>The class must store <strong>any callable object</strong> (function, lambda, functor) with signature R(Args...).</li><li>Support <strong>invocation via </strong><strong>operator()</strong>.</li><li>Provide <strong>copy and move semantics</strong>.</li><li>Throw <strong>std::bad_function_call</strong> if invoked when empty.</li><li>Allow checking if a callable is stored via <strong>operator bool()</strong>.</li><li>Implementation should use <strong>polymorphic cloning</strong> to correctly copy stored callables.</li></ul><pre>template&lt;typename&gt;<br>class Function;<br><br>template&lt;typename R, typename... Args&gt;<br>class Function&lt;R(Args...)&gt;<br>{<br>public:<br>    Function() noexcept = default;<br><br>    template&lt;typename F&gt;<br>    Function(F f);<br><br>    Function(Function&amp;&amp; other) noexcept = default;<br>    Function&amp; operator=(Function&amp;&amp; other) noexcept = default;<br><br>    Function(const Function&amp; other);<br><br>    Function&amp; operator=(const Function&amp; other);<br><br>    R operator()(Args... args) const;<br><br>    explicit operator bool() const noexcept;<br>private:<br>    struct ICallable {<br>            virtual R invoke(Args...) const  = 0;<br>            virtual std::unique_ptr&lt;ICallable&gt; clone() const  = 0;<br>            virtual ~ICallable() = default;<br>        };<br><br>    template&lt;typename FunctType&gt;<br>    struct Callable : ICallable<br>    {<br>        FunctType m_function;<br>        explicit Callable(FunctType f);<br>        R invoke(Args ...args) const override;<br>        std::unique_ptr&lt;ICallable&gt; clone() const override;<br>    };<br><br>    std::unique_ptr&lt;ICallable&gt; m_callable;<br>};</pre><h3>Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*ELpMi9jRcspbFPT15GoGwg.png" /><figcaption>canonical implementation</figcaption></figure><p>Let’s move with canonical implementation. We will start from the most independent part of the solution and move toward the most dependent one.</p><h3>ICallable</h3><p>ICallable is an <strong>abstract interface</strong> used for <strong>type erasure</strong>. It provides a common base for all callable objects stored inside Function.</p><pre>struct ICallable {<br>        virtual R invoke(Args...) const  = 0;<br>        virtual std::unique_ptr&lt;ICallable&gt; clone() const  = 0;<br>        virtual ~ICallable() = default;<br>    };</pre><h4>Methods</h4><p><strong>virtual R invoke(Args...) const = 0;</strong></p><ul><li>A pure virtual method responsible for <strong>calling the stored callable object</strong>.</li><li>Each derived implementation (Callable&lt;F&gt;) overrides this method and invokes its specific function, lambda, or functor.</li></ul><p><strong>virtual std::unique_ptr&lt;ICallable&gt; clone() const = 0;</strong></p><ul><li>Creates a <strong>polymorphic copy</strong> of the stored callable.</li><li>This enables correct <strong>copy semantics</strong> for Function, since the actual callable type is erased.</li></ul><p><strong>virtual ~ICallable() = default;</strong></p><ul><li>A <strong>virtual destructor</strong> ensuring that derived objects (Callable&lt;F&gt;) are destroyed correctly through a base pointer (ICallable).</li></ul><h3>Callable&lt;F&gt;</h3><p>Callable is a <strong>template wrapper that stores a concrete callable object</strong> (function, lambda, or functor) and adapts it to the ICallable interface.</p><pre>template&lt;typename FunctType&gt;<br>struct Callable : ICallable<br>{<br>    FunctType m_function;<br>    explicit Callable(FunctType f) : m_function(std::move(f)) {}<br>    R invoke(Args ...args) const override {<br>        return m_function(std::forward&lt;Args&gt;(args)...);<br>    }<br>    std::unique_ptr&lt;ICallable&gt; clone() const override {<br>        return std::make_unique&lt;Callable&gt;(m_function);<br>    }<br>};</pre><h4>Components</h4><p><strong>FunctType m_function;</strong><br> Stores the actual callable object (e.g., a lambda or function object).</p><p><strong>explicit Callable(FunctType f) : m_function(std::move(f)) {}</strong><br> Constructor that initializes the stored callable by moving it into m_function.</p><p><strong>R invoke(Args... args) const override</strong><br> Implements the ICallable interface method.<br> It <strong>invokes the stored callable</strong> with the provided arguments and returns the result.</p><p><strong>std::unique_ptr&lt;ICallable&gt; clone() const override</strong><br> Creates a <strong>polymorphic copy</strong> of the object.<br> This allows the Function wrapper to correctly copy the stored callable even though its concrete type is erased.</p><h4>Role in the design</h4><p>Callable is the <strong>concrete implementation used for type erasure</strong>.<br> Each stored callable type (lambda, function pointer, functor) gets wrapped in its own Callable&lt;FunctType&gt; object that is accessed through the ICallable interface.</p><h3>Function</h3><p>Function&lt;R(Args...)&gt; is a <strong>type-erased callable wrapper</strong> similar to std::function. It can store and invoke <strong>any callable object</strong> (function, lambda, functor) with the signature R(Args...).</p><pre>class Function&lt;R(Args...)&gt;<br>{<br>public:<br>    Function() noexcept = default;<br><br>    template&lt;typename F&gt;<br>    Function(F f) : m_callable(std::make_unique&lt;Callable&lt;F&gt;&gt;(std::move(f))) {}<br><br>    Function(Function&amp;&amp; other) noexcept = default;<br>    Function&amp; operator=(Function&amp;&amp; other) noexcept = default;<br><br>    Function(const Function&amp; other) :<br>       m_callable(other.m_callable ? other.m_callable-&gt;clone() : nullptr) {}<br>    Function&amp; operator=(const Function&amp; other)<br>    {<br>        m_callable = other.m_callable ? other.m_callable-&gt;clone() : nullptr;<br>        return *this;<br>    }<br><br>    R operator()(Args... args) const {<br>        if (!m_callable)<br>           throw std::bad_function_call{};<br><br>        return m_callable-&gt;invoke(std::forward&lt;Args&gt;(args)...);<br>    }<br><br>    explicit operator bool() const noexcept {return m_callable != nullptr;}<br>};</pre><h4>Constructors</h4><p><strong>Function() noexcept = default;</strong><br> Creates an <strong>empty function object</strong> with no stored callable.</p><p><strong>template&lt;typename F&gt; Function(F f)</strong><br> A templated constructor that accepts <strong>any callable type</strong>.<br> The callable is wrapped inside Callable&lt;F&gt; and stored via std::unique_ptr&lt;ICallable&gt;.</p><h4>Move semantics</h4><p><strong>Function(Function&amp;&amp; other) noexcept = default;</strong><br> Move constructor that transfers ownership of the stored callable.</p><p><strong>Function&amp; operator=(Function&amp;&amp; other) noexcept = default;</strong><br> Move assignment operator that moves the internal pointer from another Function.</p><h4>Copy semantics</h4><p><strong>Function(const Function&amp; other)</strong><br> Copy constructor that creates a <strong>deep copy</strong> of the stored callable using the virtual clone() method.</p><p><strong>Function&amp; operator=(const Function&amp; other)</strong><br> Copy assignment operator that replaces the current callable with a <strong>cloned copy</strong> of the other object&#39;s callable.</p><h4>Invocation</h4><p><strong>R operator()(Args... args) const</strong><br> Calls the stored callable.<br> If the object is empty, it throws std::bad_function_call.</p><h4>State check</h4><p><strong>explicit operator bool() const noexcept</strong><br> Allows checking whether a callable is stored.<br> Returns true if m_callable is not nullptr.</p><h4>Role in the design</h4><p>This class provides a <strong>uniform interface for invoking different callable types</strong> while hiding their concrete types using <strong>type erasure and polymorphism</strong>.</p><h3>Full code and tests</h3><pre>#include &lt;iostream&gt;<br>#include &lt;functional&gt;<br>#include &lt;memory&gt;<br><br>template&lt;typename&gt;<br>class Function;<br><br>template&lt;typename R, typename... Args&gt;<br>class Function&lt;R(Args...)&gt;<br>{<br>public:<br>    Function() noexcept = default;<br><br>    template&lt;typename F&gt;<br>    Function(F f) : m_callable(std::make_unique&lt;Callable&lt;F&gt;&gt;(std::move(f))) {}<br><br>    Function(Function&amp;&amp; other) noexcept = default;<br>    Function&amp; operator=(Function&amp;&amp; other) noexcept = default;<br><br>    Function(const Function&amp; other) :<br>       m_callable(other.m_callable ? other.m_callable-&gt;clone() : nullptr) {}<br>    Function&amp; operator=(const Function&amp; other)<br>    {<br>        m_callable = other.m_callable ? other.m_callable-&gt;clone() : nullptr;<br>        return *this;<br>    }<br><br>    R operator()(Args... args) const {<br>        if (!m_callable)<br>           throw std::bad_function_call{};<br><br>        return m_callable-&gt;invoke(std::forward&lt;Args&gt;(args)...);<br>    }<br><br>    explicit operator bool() const noexcept {return m_callable != nullptr;}<br>private:<br>    struct ICallable {<br>            virtual R invoke(Args...) const  = 0;<br>            virtual std::unique_ptr&lt;ICallable&gt; clone() const  = 0;<br>            virtual ~ICallable() = default;<br>        };<br><br>    template&lt;typename FunctType&gt;<br>    struct Callable : ICallable<br>    {<br>        FunctType m_function;<br>        explicit Callable(FunctType f) : m_function(std::move(f)) {}<br>        R invoke(Args ...args) const override {<br>            return m_function(std::forward&lt;Args&gt;(args)...);<br>        }<br>        std::unique_ptr&lt;ICallable&gt; clone() const override {<br>            return std::make_unique&lt;Callable&gt;(m_function);<br>        }<br>    };<br><br>    std::unique_ptr&lt;ICallable&gt; m_callable;<br>};<br><br>int passed = 0;<br>int failed = 0;<br><br>void check(bool condition, const char* name) {<br>    if (condition) { std::cout &lt;&lt; &quot;[PASS] &quot; &lt;&lt; name &lt;&lt; &#39;\n&#39;; ++passed; }<br>    else           { std::cout &lt;&lt; &quot;[FAIL] &quot; &lt;&lt; name &lt;&lt; &#39;\n&#39;; ++failed; }<br>}<br><br>int main() {<br>    // Basic lambda<br>    Function&lt;int(int, int)&gt; add = [](int a, int b) { return a + b; };<br>    check(add(2, 3) == 5, &quot;lambda: add(2,3) == 5&quot;);<br><br>    // Default constructed — operator bool<br>    Function&lt;int(int)&gt; empty;<br>    check(!empty, &quot;default constructed is falsy&quot;);<br><br>    // After assignment — operator bool<br>    empty = [](int x) { return x * 2; };<br>    check(!!empty, &quot;after assignment is truthy&quot;);<br>    check(empty(4) == 8, &quot;assigned lambda: empty(4) == 8&quot;);<br><br>    // Copy constructor<br>    Function&lt;int(int)&gt; copy = empty;<br>    check(copy(5) == 10, &quot;copy ctor: copy(5) == 10&quot;);<br><br>    // Copy is independent<br>    empty = [](int x) { return x + 1; };<br>    check(copy(5) == 10, &quot;copy is independent after reassigning original&quot;);<br><br>    // Move constructor<br>    Function&lt;int(int)&gt; source = [](int x) { return x * x; };<br>    Function&lt;int(int)&gt; moved = std::move(source);<br>    check(!source,         &quot;moved-from is falsy&quot;);<br>    check(moved(6) == 36,  &quot;move ctor: moved(6) == 36&quot;);<br><br>    // bad_function_call<br>    Function&lt;int(int)&gt; bad;<br>    bool threw = false;<br>    try { bad(1); } catch (const std::bad_function_call&amp;) { threw = true; }<br>    check(threw, &quot;empty call throws bad_function_call&quot;);<br><br>    // Capture by value<br>    int factor = 3;<br>    Function&lt;int(int)&gt; mul = [factor](int x) { return x * factor; };<br>    check(mul(7) == 21, &quot;capture by value: mul(7) == 21&quot;);<br><br>    // Capture by reference<br>    int counter = 0;<br>    Function&lt;void()&gt; inc = [&amp;counter]{ ++counter; };<br>    inc(); inc(); inc();<br>    check(counter == 3, &quot;capture by ref: counter == 3 after 3 calls&quot;);<br><br>    // Returning void<br>    bool called = false;<br>    Function&lt;void(int)&gt; side = [&amp;called](int){ called = true; };<br>    side(0);<br>    check(called, &quot;void return type works&quot;);<br><br>    // Free function pointer<br>    Function&lt;int(int, int)&gt; fp = [](int a, int b){ return a - b; };<br>    check(fp(10, 4) == 6, &quot;function pointer style: fp(10,4) == 6&quot;);<br><br>    std::cout &lt;&lt; &#39;\n&#39; &lt;&lt; passed &lt;&lt; &quot; passed, &quot; &lt;&lt; failed &lt;&lt; &quot; failed\n&quot;;<br>    return failed == 0 ? 0 : 1;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*hC5yHZTmkIFUS3w0ioFGgg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86c6aba81f73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ home work : Lock free stack]]></title>
            <link>https://olehslabak.medium.com/c-home-work-lock-free-stack-666573aba149?source=rss-850fc6e62b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/666573aba149</guid>
            <category><![CDATA[lock-free]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Oleh Slabak]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 12:24:55 GMT</pubDate>
            <atom:updated>2026-03-10T08:33:51.185Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>lock-free stack</strong> is a concurrent data structure that allows multiple threads to perform operations like push and pop simultaneously without using traditional mutual exclusion locks (mutexes or spinlocks).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_29BUMJFcKtqrr90" /><figcaption>Photo by <a href="https://unsplash.com/@diesektion?utm_source=medium&amp;utm_medium=referral">Robert Anasch</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Requirements</h3><p><strong>Basic requirements for a lock-free stack (Treiber stack):</strong></p><ol><li><strong>Lock-free progress</strong></li><li><strong>Atomic head pointer</strong></li><li><strong>CAS-based updates</strong></li><li><strong>Correct memory ordering</strong></li><li><strong>ABA protection</strong></li><li><strong>Safe memory reclamation</strong></li><li><strong>Linearizability</strong></li><li><strong>Thread safety</strong></li></ol><p><strong>Data structures for a lock-free stack</strong> (specifically a <strong>Treiber stack</strong>) implemented with C++ atomics.</p><pre>template&lt;typename T&gt;<br>struct List {<br>    T value;<br>    List* next = nullptr;<br>    List(T value) : value(value) {}<br>};<br><br>template&lt;typename T&gt;<br>struct TaggedPtr {<br>    List&lt;T&gt;* ptr;<br>    size_t tag;<br>    TaggedPtr(List&lt;T&gt;* p=nullptr, size_t t=0) : ptr(p), tag(t) {}<br>};<br><br>template&lt;typename T&gt;<br>class LockFreeStack<br>{<br>public:<br>    void push(T value);<br><br>    std::optional&lt;T&gt; pop();<br>     LockFreeStack() :  head(TaggedPtr&lt;T&gt;{nullptr, 0}) {}<br>    ~LockFreeStack();<br>    }<br>private:<br>    std::atomic&lt;TaggedPtr&lt;T&gt;&gt; head;<br>};</pre><h3>Why it is called lock-free</h3><p>Because it guarantees:</p><blockquote>No mutex<br>No blocking<br>At least one thread always makes progress</blockquote><p>Threads compete using <strong>atomic CAS</strong>, not locks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*QGtMm-NwIKOBo2fRNrT8oQ.png" /><figcaption>Overall architecture</figcaption></figure><h3>Implementation</h3><h4>Destructor</h4><p>The destructor <strong>atomically detaches the entire stack</strong> by setting the head to nullptr, then <strong>iterates through the linked list and deletes all remaining nodes</strong>, freeing the stack’s memory.</p><pre>    ~LockFreeStack() {<br>         TaggedPtr&lt;T&gt; old = head.exchange(TaggedPtr&lt;T&gt;{nullptr, 0},<br>                                             std::memory_order_acquire);<br>         List&lt;T&gt;* node = old.ptr;<br><br>         while (node) {<br>             List&lt;T&gt;* next = node-&gt;next;<br>             delete node;<br>             node = next;<br>         }<br>    }</pre><h4>push</h4><p>This function <strong>pushes a new element onto a lock-free stack</strong> using a CAS loop.</p><p>It allocates a new node, links it to the current stack head, and then <strong>atomically updates the head pointer with </strong><strong>compare_exchange_weak</strong>.<br> If another thread modifies the stack concurrently, the operation retries until it succeeds. The <strong>tag counter is incremented to prevent the ABA problem</strong>.</p><pre>template&lt;typename T&gt;<br>void LockFreeStack&lt;T&gt;::push(T value) {<br>    auto newNode = new List&lt;T&gt;(value);<br>    auto oldHead = head.load(std::memory_order_relaxed); // read the current stack head (pointer + tag)<br>    TaggedPtr&lt;T&gt; newHead;<br>    do {<br>        newNode-&gt;next = oldHead.ptr;<br>        newHead = {newNode, oldHead.tag + 1}; // create a new head: pointer to new node and increment tag (ABA protection)<br>    } while (!head.compare_exchange_weak(oldHead, // try to atomically replace head<br>              newHead, <br>              std::memory_order_release, // ensure node initialization is visible to other threads<br>              std::memory_order_relaxed)); // memory order used when CAS fails<br>}</pre><h4>pop</h4><p>This function <strong>removes and returns the top element from a lock-free stack</strong> using a CAS loop.<br> It reads the current head, attempts to atomically move the head to the next node, and if successful returns the popped value. If the stack is empty, it returns std::nullopt. The <strong>tag counter is incremented to prevent the ABA problem</strong>.</p><pre>template&lt;typename T&gt;<br>std::optional&lt;T&gt; LockFreeStack&lt;T&gt;::pop() {<br>    auto oldHead = head.load(std::memory_order_acquire); // atomically read the current stack head (pointer + tag)<br>    TaggedPtr&lt;T&gt; newHead;<br><br>    while (oldHead.ptr) {<br>       // prepare the new head: move to next node and increment tag (ABA protection)<br>        newHead = {oldHead.ptr-&gt;next, oldHead.tag + 1}; <br><br>        // attempt to atomically replace head with newHead<br>        // if another thread modified head, oldHead will be updated and the loop retries<br>        if (head.compare_exchange_weak(oldHead, newHead,<br>            std::memory_order_acq_rel,<br>            std::memory_order_relaxed))<br>        {<br>            auto value = oldHead.ptr-&gt;value;<br>            return value;<br>        }<br>    }<br><br>    return std::nullopt;<br>}</pre><h3><strong>Conclusion</strong></h3><p><strong>Thread safety</strong><br> push() and pop() are <strong>thread-safe</strong> because they modify the shared state (head) only through atomic operations (compare_exchange). Multiple threads can call these methods concurrently without data races.</p><p><strong>Lock-free property</strong><br> The implementation is <strong>lock-free</strong>. It does not use mutexes or blocking primitives; instead it relies on CAS retry loops. If multiple threads compete, at least <strong>one thread will always make progress</strong>, which satisfies the definition of a lock-free algorithm.</p><p><strong>ABA protection</strong><br> The use of TaggedPtr (pointer + version counter) helps prevent the <strong>ABA problem</strong>, ensuring that a CAS operation fails if the head changed and later returned to the same pointer value.</p><p><strong>Memory management limitation</strong><br> Nodes removed by pop() are <strong>not deleted immediately</strong>, which avoids use-after-free issues but causes temporary memory retention until the destructor runs. Production lock-free stacks usually require <strong>hazard pointers or epoch-based reclamation</strong> for safe memory reclamation.</p><h3>Full code &amp; test</h3><pre>#include &lt;iostream&gt;<br>#include &lt;optional&gt;<br>#include &lt;atomic&gt;<br>template&lt;typename T&gt;<br>struct List {<br>    T value;<br>    List* next = nullptr;<br>    List(T value) : value(value) {}<br><br>};<br><br>template&lt;typename T&gt;<br>struct TaggedPtr {<br>    List&lt;T&gt;* ptr;<br>    size_t tag;<br>    TaggedPtr(List&lt;T&gt;* p=nullptr, size_t t=0) : ptr(p), tag(t) {}<br>};<br><br>template&lt;typename T&gt;<br>class LockFreeStack<br>{<br>public:<br>    void push(T value);<br><br>    std::optional&lt;T&gt; pop();<br>     LockFreeStack() :  head(TaggedPtr&lt;T&gt;{nullptr, 0}) {}<br>    ~LockFreeStack() {<br>         TaggedPtr&lt;T&gt; old = head.exchange(TaggedPtr&lt;T&gt;{nullptr, 0},<br>                                             std::memory_order_acquire);<br><br>         List&lt;T&gt;* node = old.ptr;<br><br>         while (node) {<br>             List&lt;T&gt;* next = node-&gt;next;<br>             delete node;<br>             node = next;<br>         }<br>    }<br>private:<br>    std::atomic&lt;TaggedPtr&lt;T&gt;&gt; head;<br>};<br><br>template&lt;typename T&gt;<br>void LockFreeStack&lt;T&gt;::push(T value) {<br>    auto newNode = new List&lt;T&gt;(value);<br>    auto oldHead = head.load(std::memory_order_relaxed);<br>    TaggedPtr&lt;T&gt; newHead;<br>    do {<br>        newNode-&gt;next = oldHead.ptr;<br>        newHead = {newNode, oldHead.tag + 1};<br>    } while (!head.compare_exchange_weak(oldHead, newHead, std::memory_order_release, std::memory_order_relaxed));<br>}<br><br>template&lt;typename T&gt;<br>std::optional&lt;T&gt; LockFreeStack&lt;T&gt;::pop() {<br>    auto oldHead = head.load(std::memory_order_acquire);<br>    TaggedPtr&lt;T&gt; newHead;<br><br>    while (oldHead.ptr) {<br>        newHead = {oldHead.ptr-&gt;next, oldHead.tag + 1};<br><br>        if (head.compare_exchange_weak(oldHead, newHead, std::memory_order_acq_rel, std::memory_order_relaxed)) {<br>            auto value = oldHead.ptr-&gt;value;<br>            return value;<br>        }<br>    }<br><br>    return std::nullopt;<br>}<br><br>void test_basic_push_pop()<br>{<br>    LockFreeStack&lt;int&gt; stack;<br><br>    stack.push(10);<br><br>    auto v = stack.pop();<br><br>    if (!v || *v != 10)<br>        std::cout &lt;&lt; &quot;FAIL: basic push/pop\n&quot;;<br>    else<br>        std::cout &lt;&lt; &quot;PASS: basic push/pop\n&quot;;<br>}<br><br>void test_lifo()<br>{<br>    LockFreeStack&lt;int&gt; stack;<br><br>    stack.push(1);<br>    stack.push(2);<br>    stack.push(3);<br><br>    auto a = stack.pop();<br>    auto b = stack.pop();<br>    auto c = stack.pop();<br><br>    if (!a || !b || !c)<br>        std::cout &lt;&lt; &quot;FAIL: lifo missing values\n&quot;;<br>    else if (*a != 3 || *b != 2 || *c != 1)<br>        std::cout &lt;&lt; &quot;FAIL: lifo order wrong\n&quot;;<br>    else<br>        std::cout &lt;&lt; &quot;PASS: lifo\n&quot;;<br>}<br><br>void test_pop_empty()<br>{<br>    LockFreeStack&lt;int&gt; stack;<br><br>    auto v = stack.pop();<br><br>    if (v)<br>        std::cout &lt;&lt; &quot;FAIL: pop empty should return nullopt\n&quot;;<br>    else<br>        std::cout &lt;&lt; &quot;PASS: pop empty\n&quot;;<br>}<br><br>void test_many()<br>{<br>    LockFreeStack&lt;int&gt; stack;<br><br>    for (int i = 0; i &lt; 1000; i++)<br>        stack.push(i);<br><br>    int count = 0;<br><br>    while (true)<br>    {<br>        auto v = stack.pop();<br>        if (!v)<br>            break;<br><br>        count++;<br>    }<br><br>    if (count != 1000)<br>        std::cout &lt;&lt; &quot;FAIL: lost elements\n&quot;;<br>    else<br>        std::cout &lt;&lt; &quot;PASS: many push/pop\n&quot;;<br>}<br><br>#include &lt;thread&gt;<br><br>void test_multithread_push()<br>{<br>    LockFreeStack&lt;int&gt; stack;<br><br>    auto worker = [&amp;stack]()<br>    {<br>        for (int i = 0; i &lt; 10000; i++)<br>            stack.push(i);<br>    };<br><br>    std::thread t1(worker);<br>    std::thread t2(worker);<br><br>    t1.join();<br>    t2.join();<br><br>    int count = 0;<br><br>    while (stack.pop())<br>        count++;<br><br>    if (count != 20000)<br>        std::cout &lt;&lt; &quot;FAIL: multithread push lost elements\n&quot;;<br>    else<br>        std::cout &lt;&lt; &quot;PASS: multithread push\n&quot;;<br>}<br><br>void test_multithread_push_pop()<br>{<br>    LockFreeStack&lt;int&gt; stack;<br><br>    auto push_worker = [&amp;stack]()<br>    {<br>        for (int i = 0; i &lt; 5000; i++)<br>            stack.push(i);<br>    };<br><br>    auto pop_worker = [&amp;stack]()<br>    {<br>        for (int i = 0; i &lt; 5000; i++)<br>            stack.pop();<br>    };<br><br>    std::thread t1(push_worker);<br>    std::thread t2(push_worker);<br>    std::thread t3(pop_worker);<br>    std::thread t4(pop_worker);<br><br>    t1.join();<br>    t2.join();<br>    t3.join();<br>    t4.join();<br><br>    int remaining = 0;<br><br>    while (stack.pop())<br>        remaining++;<br><br>    if (remaining &gt; 10000)<br>        std::cout &lt;&lt; &quot;FAIL: inconsistent state\n&quot;;<br>    else<br>        std::cout &lt;&lt; &quot;PASS: multithread push/pop\n&quot;;<br>}<br><br>void test_aba() {<br>    LockFreeStack&lt;int&gt; stack;<br>    stack.push(1);<br>    stack.pop();<br>    stack.push(2);<br>    auto value = stack.pop();<br>    if (value  == 2) {<br>        std::cout &lt;&lt; &quot;PASS: aba\n&quot;;<br>    }<br>    else {<br>        std::cout &lt;&lt; &quot;FAIL: aba\n&quot;;<br>    }<br>}<br><br>int main() {<br>    test_basic_push_pop();<br>    test_lifo();<br>    test_pop_empty();<br>    test_many();<br>    test_aba();<br>    test_multithread_push();<br>    test_multithread_push_pop();<br><br>    return 0;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*ORyYx4zssLeOcd0SMiSM5w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=666573aba149" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C++ home work : Thread-Safe Observer Pattern]]></title>
            <link>https://olehslabak.medium.com/c-home-work-thread-safe-observer-pattern-e4cfcab15133?source=rss-850fc6e62b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4cfcab15133</guid>
            <category><![CDATA[thread-safe]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Oleh Slabak]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 20:34:02 GMT</pubDate>
            <atom:updated>2026-03-03T20:34:02.704Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://en.wikipedia.org/wiki/Software_design">software design</a> and <a href="https://en.wikipedia.org/wiki/Software_engineering">software engineering</a>, the <strong>observer pattern</strong> is a <a href="https://en.wikipedia.org/wiki/Software_design_pattern">software design pattern</a> in which an object, called the <strong><em>subject</em></strong> (also known as <strong><em>event source</em></strong> or <strong><em>event stream</em></strong>), maintains a list of its dependents, called <strong>observers</strong> (also known as <strong><em>event sinks</em></strong>), and automatically notifies them of any <a href="https://en.wikipedia.org/wiki/State_(computer_science)">state changes</a>, typically by calling one of their <a href="https://en.wikipedia.org/wiki/Method_(computer_science)">methods</a>.</p><p><a href="https://en.wikipedia.org/wiki/Observer_pattern">Wiki links</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3SQ3IkydxC8i90-s" /><figcaption>Photo by <a href="https://unsplash.com/@dlerman6?utm_source=medium&amp;utm_medium=referral">Daniel Lerman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Requirements</h3><p>Implement a template Thread-Safe Observer Pattern class:</p><pre>template&lt;typename Event&gt;<br>class EventDispatcher<br>{<br>public:<br>    using Callback = std::function&lt;void(const Event&amp;)&gt;;<br><br>    size_t subscribe(Callback cb);<br>    void unsubscribe(size_t id);<br><br>    void notify(const Event&amp; event);<br>};</pre><h3>Behavior</h3><h3>subscribe</h3><ul><li>Adds a callback</li><li>Returns a unique ID</li><li>Must be thread-safe</li></ul><h3>unsubscribe</h3><ul><li>Removes a callback by ID</li><li>Must be safe when called concurrently with notify</li></ul><h3>notify</h3><ul><li>Invokes all currently subscribed callbacks</li><li>Must be thread-safe</li><li>Must not hold a lock while executing callbacks</li></ul><h3>Implementation</h3><p>Let’s add additional private and public members/using that we will use to achieve our goal.</p><pre>public:<br>    using ObserverMap = std::unordered_map&lt;size_t, Callback&gt;;<br>private:<br>// I&#39;m planning to use a mutex to protect the subscribe and unsubscribe operations.<br>    std::mutex m_mutex; <br>    std::size_t m_nextID = 0; // unique observer id <br>    std::shared_ptr&lt;ObserverMap&gt; m_observers{std::make_shared&lt;ObserverMap&gt;()};</pre><h3>Let’s look at the subscribe function.</h3><pre>template&lt;typename Event&gt;<br>size_t EventDispatcher&lt;Event&gt;::subscribe(Callback cb) {<br>    std::scoped_lock lock(m_mutex); // Lock acquisition<br>    auto id = m_nextID++; // Generate unique ID<br>    auto oldMap = std::atomic_load(&amp;m_observers); // Atomic load of current snapshot<br>    auto newMap = std::make_shared&lt;ObserverMap&gt;(*oldMap); // Create a new map copy<br>    newMap-&gt;emplace(id, std::move(cb)); // Add new callback<br>    std::atomic_store(&amp;m_observers, std::const_pointer_cast&lt;ObserverMap&gt;(newMap)); // Atomically publish new version<br>    return id; // Return ID<br>}</pre><h4>Lock acquisition</h4><pre>std::scoped_lock lock(m_mutex);</pre><ul><li>Prevents concurrent subscribe/unsubscribe</li></ul><p>Ensures:</p><ul><li>safe increment of m_nextID</li><li>consistent update of m_observers</li><li>notify() does not take this lock</li></ul><h4>Generate unique ID</h4><pre>auto id = m_nextID++;</pre><ul><li>Unique observer ID</li><li>Protected by mutex → no race condition</li></ul><h4>Atomic load of current snapshot</h4><pre>auto oldMap = std::atomic_load(&amp;m_observers);</pre><p>What happens:</p><ul><li>Atomically copies the shared_ptr</li><li>Increments reference count</li><li>We now have a stable snapshot</li><li>Even if another thread modifies m_observers,<br> this snapshot remains valid</li></ul><p>This is the core of the copy-on-write design.</p><h4>Create a new map copy</h4><pre>auto newMap = std::make_shared&lt;ObserverMap&gt;(*oldMap);</pre><ul><li>Creates a full copy of the map</li><li>We modify the new copy</li><li>The old snapshot remains unchanged</li></ul><p>This is copy-on-write.</p><h4>Add new callback</h4><pre>newMap-&gt;emplace(id, std::move(cb));</pre><p>Adds observer to the new version only.</p><h4>Atomically publish new version</h4><pre>std::atomic_store(&amp;m_observers, newMap);</pre><ul><li>Atomically replaces the shared_ptr</li><li>Future notify() calls see the new version</li><li>Ongoing notify() calls keep using the old version</li></ul><p>shared_ptr ensures safe lifetime.</p><h4>Return ID</h4><p>Self-explanatory.</p><h3>Concurrency guarantees</h3><p>If:</p><p>Thread A → notify()<br> Thread B → subscribe()</p><p>Possible timeline:</p><ol><li>A loads snapshot</li><li>B creates new version</li><li>B stores new version</li><li>A continues using old snapshot safely</li></ol><p>✔ No data race<br> ✔ No iterator invalidation<br> ✔ No use-after-free<br> ✔ Strong lifetime guarantees</p><h3>Move to unsubscribe</h3><pre>template&lt;typename Event&gt;<br>void EventDispatcher&lt;Event&gt;::unsubscribe(size_t id) {<br>    std::lock_guard lock(m_mutex); // Lock acquisition<br>    auto oldMap = std::atomic_load(&amp;m_observers); // Atomic load of current snapshot<br>    auto newMap = std::make_shared&lt;ObserverMap&gt;(*oldMap); // Create a new copy (Copy-On-Write)<br>    if (newMap-&gt;erase(id)) { // Remove observer from the new version<br>       std::atomic_store(&amp;m_observers, newMap); // Atomic publish of new snapshot<br>    }<br>}</pre><h4>Lock acquisition</h4><pre>std::lock_guard lock(m_mutex);</pre><p>Prevents concurrent subscribe() and unsubscribe()</p><p>Protects:</p><ul><li>m_nextID</li><li>modifications of m_observers</li><li>notify() does NOT acquire this lock</li></ul><p>This ensures serialized modifications of the observer set.</p><h4>Atomic load of current snapshot</h4><pre>auto oldMap = std::atomic_load(&amp;m_observers);</pre><p>What happens here:</p><ul><li>Atomically copies the shared_ptr</li><li>Increments reference count</li><li>Produces a stable snapshot of the current observer map</li></ul><p>Even if another thread replaces m_observers,<br> oldMap remains valid because of shared ownership.</p><p>This is the snapshot mechanism.</p><h4>Create a new copy (Copy-On-Write)</h4><pre>auto newMap = std::make_shared&lt;ObserverMap&gt;(*oldMap);</pre><ul><li>Allocates a new unordered_map</li><li>Copies all existing observers</li><li>We will modify this new copy only</li></ul><p>The original map remains unchanged.</p><p>This prevents:</p><ul><li>iterator invalidation</li><li>races with ongoing notify()</li><li>lifetime issues</li></ul><h4>Remove observer from the new version</h4><pre>if (newMap-&gt;erase(id)) {</pre><ul><li>Attempts to erase the observer</li><li>Returns non-zero if the ID existed</li><li>If the ID was not present → no modification occurs</li></ul><p>Important:<br> This ensures we only publish a new version if something actually changed.</p><h4>Atomic publish of new snapshot</h4><pre>std::atomic_store(&amp;m_observers, newMap);</pre><p>If the observer was removed:</p><ul><li>Atomically replaces the shared_ptr</li><li>Future notify() calls will see the updated version</li><li>Ongoing notify() calls continue using their existing snapshot safely</li></ul><p>This guarantees:</p><ul><li>No data race</li><li>No use-after-free</li><li>Proper memory visibility</li></ul><h4>Concurrency Behavior</h4><p>Consider this scenario:</p><p>Thread A → notify()<br> Thread B → unsubscribe(id)</p><p>Possible timeline:</p><ol><li>A loads snapshot S₁</li><li>B creates S₂ (copy without observer)</li><li>B publishes S₂</li><li>A continues executing S₁ safely</li></ol><p>Important implication:</p><blockquote><em>If unsubscribe happens concurrently with notify, the callback might still be invoked once.</em></blockquote><p>This is expected behavior in snapshot-based designs.</p><h4>Memory Safety Guarantees</h4><p>Because m_observers is a shared_ptr:</p><ul><li>Old snapshots stay alive as long as notify holds them</li><li>No dangling pointers</li><li>No iterator invalidation</li><li>No ABA issue (since we don’t rely on CAS comparison)</li></ul><h3>Finally notify</h3><pre>template&lt;typename Event&gt;<br>void EventDispatcher&lt;Event&gt;::notify(const Event &amp;event) {<br>    auto snapshot = std::atomic_load(&amp;m_observers); // Atomic snapshot load<br>    for (auto &amp;[id, cb] : *snapshot) { // Iteration over snapshot<br>        cb(event); // cb(event);<br>    }<br>}</pre><h4>Atomic snapshot load</h4><pre>auto snapshot = std::atomic_load(&amp;m_observers);</pre><p>What happens here:</p><ul><li>Atomically copies the shared_ptr</li><li>Increments its reference count</li><li>Produces a stable snapshot of the current observer map</li></ul><p>This is the key operation.</p><p>Even if another thread performs:</p><ul><li>subscribe() (adds observer)</li><li>unsubscribe() (removes observer)</li></ul><p>The snapshot remains valid and independent.</p><p>This guarantees:</p><p>✔ No data race<br> ✔ No iterator invalidation<br> ✔ No use-after-free</p><h4>Iteration over snapshot</h4><pre>for (auto &amp;[id, cb] : *snapshot)</pre><p>We iterate over the copied map.</p><p>Important detail:</p><p>We are NOT iterating over m_observers directly.</p><p>We are iterating over a specific version (snapshot).</p><p>So even if the global map changes concurrently,<br> this iteration remains stable.</p><h4>Callback invocation</h4><pre>cb(event);</pre><p>The callback is executed <strong>without holding any mutex</strong>.</p><p>This is extremely important.</p><p>Why?</p><ul><li>Prevents deadlocks</li><li>Prevents reentrancy issues</li><li>Prevents blocking subscribe/unsubscribe</li><li>Avoids long critical sections</li></ul><p>If a callback:</p><ul><li>Calls unsubscribe()</li><li>Calls subscribe()</li><li>Calls notify() again</li></ul><p>It is safe.</p><p>Because the snapshot is immutable.</p><h4>Concurrency Scenarios</h4><h4>Scenario 1: subscribe during notify</h4><ol><li>Thread A loads snapshot S₁</li><li>Thread B adds observer → creates S₂</li><li>Thread B publishes S₂</li><li>Thread A continues iterating S₁</li></ol><p>Result:</p><ul><li>New observer is NOT called in this notify</li><li>Will be called in future notify calls</li></ul><p>This is expected snapshot behavior.</p><h4>Scenario 2: unsubscribe during notify</h4><ol><li>Thread A loads snapshot S₁</li><li>Thread B removes observer → creates S₂</li><li>Thread A continues iterating S₁</li></ol><p>Result:</p><ul><li>Removed observer may still be called once</li><li>Will not be called in future notify calls</li></ul><p>This is correct for snapshot semantics.</p><h4>Scenario 3: callback unsubscribes itself</h4><p>Safe.</p><p>The current snapshot still contains the callback.<br> Future snapshots will not.</p><p>No crash.<br>No invalid iterator.<br>No deadlock.</p><h4>Memory Safety Guarantees</h4><p>Because snapshot is a shared_ptr:</p><ul><li>The map stays alive during the entire notify call</li><li>Even if the dispatcher replaces m_observers</li><li>Lifetime is guaranteed by reference counting</li></ul><p>No ABA problem.<br>No dangling references.<br>No use-after-free.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*guURNtOlfK5iaHoH" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4cfcab15133" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Architectural Styles: Client–Server Architecture]]></title>
            <link>https://olehslabak.medium.com/system-architectural-styles-client-server-architecture-fb6712dd7610?source=rss-850fc6e62b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb6712dd7610</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[client-server]]></category>
            <dc:creator><![CDATA[Oleh Slabak]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 10:25:38 GMT</pubDate>
            <atom:updated>2026-02-10T10:25:38.431Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Is Client–Server Architecture?</h3><p>Client–server architecture is a distributed computing model where responsibilities are clearly separated:</p><ul><li>💻 <strong>Client</strong> — handles UI/UX, user input, and request initiation</li><li>🖧 <strong>Server</strong> — processes requests, enforces business logic, manages data, and ensures security</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*LTFEch6XidK4rCf4LiRU9A.png" /></figure><p>Clients never access data directly. All operations go through the server, which acts as a <strong>controlled gateway</strong>, improving <strong>security</strong>, <strong>maintainability</strong>, and <strong>consistency </strong>across multiple client types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BY72Q6O8AB0e2UC2" /><figcaption>Photo by <a href="https://unsplash.com/@dulhiier?utm_source=medium&amp;utm_medium=referral">Nastya Dulhiier</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>More details you may found here:</h3><blockquote><a href="https://hansinirup.medium.com/evolution-of-client-server-architecures-58e531fbf1a6">EVOLUTION OF CLIENT/SERVER ARCHITECURES</a></blockquote><blockquote><a href="https://medium.com/@mike.anderson007/the-evolution-of-server-architecture-c2568850846e">The Evolution of Server Architecture</a></blockquote><h3>How Client–Server Architecture Works</h3><p>Communication follows a <strong>request–response lifecycle</strong>:</p><ol><li>Client sends a request (HTTP, HTTPS, TCP)</li><li>Server authenticates and authorizes the request</li><li>Server executes business logic</li><li>Server queries databases or caches</li><li>Server sends a structured response</li></ol><p>Most systems are <strong>stateless</strong>, meaning each request is independent, which greatly improves scalability.</p><h3>Types of Client–Server Architectures</h3><h4>🧩 Two-Tier Architecture</h4><ul><li>Client ↔ Server/Database</li><li>Simple to implement</li><li>Limited scalability and weaker security</li><li>Used in small or legacy systems</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*RCwTklq9eDpjO8hkmNpd6A.png" /></figure><h4>🏗️ Three-Tier Architecture</h4><ul><li>Presentation layer (client)</li><li>Application layer (server)</li><li>Data layer (database)</li><li>Better separation of concerns</li><li>Easier maintenance and testing</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*t7Dehe8waqHXag5su4DRmQ.png" /></figure><h4>🌐 N-Tier (Multi-Tier) Architecture</h4><ul><li>API Gateway</li><li>Auth services</li><li>Multiple backend services</li><li>Multiple data stores</li><li>High scalability and fault tolerance</li><li>Higher operational complexity</li></ul><h3>Advantages of Client–Server Architecture</h3><ul><li><strong>Centralized Data</strong> — single source of truth</li><li><strong>Improved Security</strong> — server-side validation and encryption</li><li><strong>Easier Maintenance</strong> — update server without redeploying clients</li><li><strong>Multi-Client Support</strong> — web, mobile, desktop reuse the same APIs</li></ul><h3>Scaling the Client–Server Model</h3><p>Common scaling strategies include:</p><ul><li><strong>Vertical Scaling</strong> — stronger servers</li><li><strong>Horizontal Scaling</strong> — multiple server instances</li><li><strong>Load Balancing</strong> — distribute traffic evenly</li><li><strong>Caching</strong> — reduce database pressure</li><li><strong>Async Processing</strong> — background jobs and queues</li></ul><p>These techniques help systems scale from <strong>hundreds to millions of users</strong>.</p><h3>Real-World Applications</h3><p>🌐 <strong>Web Browsing</strong><br> Browsers request resources from servers, which respond with HTML, CSS, JavaScript, and data.</p><p>📧 <strong>Email Services</strong><br> Clients sync messages, while servers manage delivery, storage, spam filtering.</p><p>🏦 <strong>Online Banking</strong><br> Servers handle authentication, transaction validation, auditing, and encryption.</p><p>☁️ <strong>Cloud Computing</strong><br> Applications act as clients consuming cloud APIs to dynamically provision infrastructure.</p><h3>Small Pseudocode Example</h3><pre>// Client<br>request = {<br>  method: GET,<br>  url: &quot;/user/profile&quot;,<br>  headers: { Authorization: token }<br>}<br>response = send(request)<br>renderProfile(response.data)<br><br>// Server<br>handleRequest(request):<br>  user = authenticate(request.headers.Authorization)<br>  if user == null:<br>    return error(401)<br><br>  profile = database.loadUserProfile(user.id)<br>  return success(200, profile)</pre><p>Client–server architecture is the <strong>foundation of modern distributed systems</strong>.<br> Its success depends on <strong>clear separation of concerns</strong>, <strong>scalable server design</strong>, and <strong>strong security practices</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb6712dd7610" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Architectural Styles: Event-Driven Architecture]]></title>
            <link>https://olehslabak.medium.com/system-architectural-styles-event-driven-architecture-addbb8b44651?source=rss-850fc6e62b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/addbb8b44651</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[system-architecture]]></category>
            <dc:creator><![CDATA[Oleh Slabak]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 11:08:54 GMT</pubDate>
            <atom:updated>2025-10-02T11:08:54.646Z</atom:updated>
            <content:encoded><![CDATA[<p>🔌<strong>Event-Driven Architecture (EDA)</strong> is a system design style where components communicate by producing and consuming events asynchronously. Instead of direct requests, services publish events (e.g., <em>OrderPlaced</em>), and other services subscribe and react to them. This enables <strong>loose coupling, scalability, and real-time processing</strong>, making it popular in microservices, IoT, finance, and streaming platforms. However, it introduces challenges with <strong>complexity, event ordering, debugging, and eventual consistency</strong>.</p><p>It’s common in:</p><ul><li><strong>Real-time applications</strong> (finance, IoT, gaming)</li><li><strong>Microservices</strong> (loosely coupled services communicating via events)</li><li><strong>Scalable distributed systems</strong> (handling large streams of data/events)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8A-UxA9fab1fuXQr" /><figcaption>Photo by <a href="https://unsplash.com/@julianhochgesang?utm_source=medium&amp;utm_medium=referral">Julian Hochgesang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🛒How Event-Driven Architecture Works</h3><ol><li><strong>Event Producer</strong> detects a change and publishes an event (e.g., “<strong><em>OrderPlaced</em></strong>”).</li><li><strong>Event Broker (Message Queue / Streaming Platform)</strong> delivers the event to interested consumers.</li><li><strong>Event Consumers</strong> react to the event (e.g., update inventory, send confirmation email).</li><li>System stays decoupled — producers don’t need to know who consumes the event.</li></ol><pre>[ Producer 🛒 ]  ---&gt;  [ Event Broker 📬 ]  ---&gt;  [ Consumer 📦 ]<br>(OrderPlaced)                                      (Updates stock, sends email)</pre><h3>📬Event-Driven Architecture and Microservices</h3><ul><li>Fits naturally with microservices: each service can publish/subscribe independently.</li><li>Promotes <strong>loose coupling</strong> and <strong>asynchronous communication</strong>.</li><li>Enables event sourcing and CQRS (Command Query Responsibility Segregation).</li><li>Example: An <strong>e-commerce system</strong> — checkout service publishes “OrderPlaced”, payment service consumes it, shipping service consumes another “OrderPaid” event, etc.</li></ul><h3>📦Real-World Examples</h3><ul><li><strong>Uber/Lyft</strong>: events track ride requests, driver updates, payments.</li><li><strong>Netflix</strong>: streaming events (watch start/stop) drive recommendations.</li><li><strong>Banking apps</strong>: transactions published as events, processed by fraud detection, balance update, notification services.</li><li><strong>IoT systems</strong>: devices sending events (temperature change, motion detected) to cloud services.</li></ul><h3>✅Advantages of Event-Driven Architecture</h3><ul><li><strong>Scalability</strong> — handle massive streams of events in parallel.</li><li><strong>Loose coupling</strong> — producers and consumers evolve independently.</li><li><strong>Real-time processing</strong> — immediate reaction to changes.</li><li><strong>Flexibility &amp; extensibility</strong> — new consumers can subscribe without touching existing code.</li><li><strong>Resilience</strong> — if one consumer fails, events can be retried later.</li></ul><h3>❌Disadvantages</h3><ol><li><strong>Complexity</strong></li></ol><ul><li>Designing asynchronous workflows and managing dependencies is harder than synchronous APIs.</li><li>Requires robust monitoring and tooling.</li></ul><p><strong>2. Event Ordering</strong></p><ul><li>Events may arrive out of order, leading to race conditions or incorrect states if not handled carefully.</li></ul><p><strong>3. Eventual Consistency</strong></p><ul><li>Consumers might process events at different times, so the system may not always be instantly consistent.</li></ul><p><strong>4. Debugging and Troubleshooting</strong></p><ul><li>Tracing an event flow across multiple services is difficult.</li><li>Requires distributed logging, correlation IDs, or observability tools.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FB07km%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FB07km%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FB07km%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="1002" height="570" frameborder="0" scrolling="no"><a href="https://medium.com/media/0600174eb28bec3151fa2111c7f50f0c/href">https://medium.com/media/0600174eb28bec3151fa2111c7f50f0c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MsWRGop67CuCwAHV" /><figcaption>Photo by <a href="https://unsplash.com/@fmat?utm_source=medium&amp;utm_medium=referral">Max Fomin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=addbb8b44651" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Architectural Styles: Serverless Architecture]]></title>
            <link>https://olehslabak.medium.com/system-architectural-styles-serverless-architecture-e9bf70d7fbfe?source=rss-850fc6e62b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9bf70d7fbfe</guid>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Oleh Slabak]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 10:02:13 GMT</pubDate>
            <atom:updated>2025-08-11T10:04:01.281Z</atom:updated>
            <content:encoded><![CDATA[<p>🌞Serverless computing is a cloud execution model where developers build and deploy code without managing underlying servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qvw32ruyH7mQhE8s" /><figcaption>Photo by <a href="https://unsplash.com/@taylorvanriper925?utm_source=medium&amp;utm_medium=referral">Taylor Van Riper</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🔅What is Serverless Computing?</h3><p>Serverless computing is a cloud execution model where developers build and deploy code without managing underlying servers.</p><ul><li>The cloud provider dynamically provisions, scales, and manages infrastructure.</li><li>Developers focus solely on writing business logic.</li><li>Billing is based on <strong>actual usage</strong> (execution time, memory consumed) rather than fixed server costs.</li></ul><blockquote><strong><em>Key idea:</em></strong> No server management for the developer — but servers still exist, managed by the provider.</blockquote><h3>🔆Serverless Computing Providers and Platforms</h3><p>Popular providers:</p><ul><li><a href="https://aws.amazon.com/lambda/"><strong>AWS Lambda</strong></a> (Amazon Web Services)</li><li><a href="https://azure.microsoft.com/en-us/products/functions"><strong>Azure Functions</strong></a> (Microsoft Azure)</li><li><a href="https://cloud.google.com/"><strong>Google Cloud Functions</strong> </a>(Google Cloud Platform)</li><li><a href="https://workers.cloudflare.com/"><strong>Cloudflare Workers</strong></a></li><li><a href="https://www.openfaas.com/"><strong>OpenFaaS</strong> </a>(open source, Kubernetes-based)</li><li><a href="https://cloud.ibm.com/catalog#highlights"><strong>IBM Cloud Functions</strong></a> (based on Apache OpenWhisk)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tcT_ExkXw5KPQvrB.jpg" /><figcaption>img source: <a href="https://www.kofi-group.com/serverless-architecture-explained-in-10-minutes/">https://www.kofi-group.com/serverless-architecture-explained-in-10-minutes/</a></figcaption></figure><h3>🏄Steps for Developing Serverless Applications</h3><ol><li><strong>Define the Trigger/Event</strong><br> (HTTP request, file upload, database change, queue message, IoT event, cron schedule).</li><li><strong>Write the Function</strong><br> Implement logic that responds to the trigger.</li><li><strong>Configure Event Binding</strong><br> Link the function to its event source.</li><li><strong>Deploy to Cloud Provider</strong><br> Package and upload code (via CLI, console, or CI/CD pipeline).</li><li><strong>Test and Monitor</strong><br> Validate performance and correctness in production.</li><li><strong>Iterate</strong><br> Optimize for cost, scalability, and reliability.</li></ol><h3>🌅Serverless Application Design Patterns</h3><ul><li><strong>Event-Driven Functions</strong> — Single-purpose functions triggered by events.</li><li><strong>Function Chaining</strong> — Sequential execution of multiple functions.</li><li><strong>Fan-Out/Fan-In</strong> — One event triggers multiple parallel functions whose results are aggregated.</li><li><strong>Queue-Based Load Leveling</strong> — Functions read from queues to handle burst traffic.</li><li><strong>Backend for Frontend (BFF)</strong> — Separate APIs per client type, each handled by serverless functions.</li></ul><h3>🎹Integration and Orchestration</h3><ul><li><strong>Integration</strong>: Serverless functions interact with databases, APIs, queues, and storage systems.</li><li><strong>Orchestration</strong>: Managed workflows coordinate multiple serverless functions (e.g., AWS Step Functions, Azure Durable Functions).</li></ul><h3>💪Scaling and Performance Considerations</h3><ul><li>Serverless platforms <strong>auto-scale</strong> per event load.</li><li><strong>Cold starts</strong>: First execution after inactivity may be slower.</li><li>Concurrency limits may apply (tunable in some platforms).</li><li>Optimize code/package size to reduce startup latency.</li></ul><blockquote>More about <strong>Scalability: </strong><a href="https://medium.com/@olehslabak/system-design-key-concepts-8fa04c5d5119">Core Principles of System Design: Scalability</a></blockquote><h3>💣Security Best Practices</h3><ul><li>Follow <strong>principle of least privilege</strong> in IAM policies.</li><li>Avoid embedding secrets in code — use secret managers.</li><li>Validate all inputs (especially from event sources).</li><li>Keep functions stateless and isolate sensitive logic.</li><li>Monitor for anomalous behavior.</li></ul><h3>🎉Serverless Architecture Use Cases</h3><p><strong>Web Applications</strong> — Dynamic APIs, single-page app backends.</p><p><strong>Data Processing:</strong></p><ul><li><strong>Real-Time Streams</strong> — IoT data, log ingestion, social media feeds.</li><li><strong>Batch Processing</strong> — Image processing, ETL pipelines, report generation.</li></ul><p><strong>Automation &amp; Orchestration</strong> — Scheduled tasks, business workflows.</p><p><strong>Microservices</strong> — Independent function-based services.</p><p><strong>DevOps &amp; CI/CD</strong> — Build automation, deployment triggers.</p><h3>💰Benefits of Serverless Architecture</h3><ul><li><strong>Cost Efficiency</strong> — Pay-per-use pricing, no idle server cost.</li><li><strong>Scalability</strong> — Automatic scaling with demand.</li><li><strong>Developer Productivity</strong> — No server management, faster iterations.</li><li><strong>Global Reach</strong> — Functions can run close to the end user via edge networks.</li></ul><h3>🔥Challenges and Considerations</h3><ol><li><strong>Cold Start Latency</strong> — Delay on first invocation after inactivity.</li><li><strong>Complexity in State Management</strong> — Functions are stateless; external storage needed.</li><li><strong>Vendor Lock-In</strong> — Difficult migration between providers.</li><li><strong>Debugging and Monitoring</strong> — Harder in distributed, event-driven systems.</li><li><strong>Resource Limits</strong> — Execution timeouts, memory caps, package size restrictions.</li></ol><h3>🎁Best Practices</h3><ol><li><strong>Design for Event-Driven Architecture</strong> — Functions should react to discrete events.</li><li><strong>Optimize Function Performance</strong> — Keep code small, warm critical paths.</li><li><strong>Implement Robust Security</strong> — Secure APIs, secrets, and dependencies.</li><li><strong>Monitor and Optimize Costs</strong> — Use provider metrics to avoid waste.</li><li><strong>Implement Observability</strong> — Logging, tracing, and alerts are essential.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FDHLqK%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FDHLqK%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FDHLqK%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="1024" height="676" frameborder="0" scrolling="no"><a href="https://medium.com/media/444c3e1307a6ea3ce3d5812a7ba360dc/href">https://medium.com/media/444c3e1307a6ea3ce3d5812a7ba360dc/href</a></iframe><h3>Useful links:</h3><p>Serverless Architecture</p><blockquote>Serverless architecture, despite its name, does not mean that servers are no longer involved. Instead, it refers to a model where the cloud provider dynamically manages the allocation of machine resources, and developers deploy their code in the form of functions or services without worrying about the underlying infrastructure.</blockquote><p><a href="https://blog.algomaster.io/p/2edeb23b-cfa5-4b24-845e-3f6f7a39d162">Serverless Architecture</a></p><p>Geeks for Geeks</p><p><a href="https://www.geeksforgeeks.org/system-design/serverless-architectures/">Serverless Architecture</a></p><p>Serverless Architecture Explained In 10 Minutes</p><p><a href="https://www.kofi-group.com/serverless-architecture-explained-in-10-minutes/">link</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YSmqGI02iM6HtLwm" /><figcaption>Photo by <a href="https://unsplash.com/@tyler_mower?utm_source=medium&amp;utm_medium=referral">Tyler Mower</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9bf70d7fbfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Architectural Styles: Microservices Architecture]]></title>
            <link>https://olehslabak.medium.com/system-architectural-styles-microservices-architecture-4a79ba8479ab?source=rss-850fc6e62b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a79ba8479ab</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-architecture]]></category>
            <dc:creator><![CDATA[Oleh Slabak]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 08:56:27 GMT</pubDate>
            <atom:updated>2025-07-31T08:57:00.077Z</atom:updated>
            <content:encoded><![CDATA[<p>🧩Microservices architecture is an approach to building software systems as a suite of <strong>small, independent services.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VNffSXRgE51TwzRc" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>📖 Definition</h3><p>Microservices architecture is an approach to building software systems as a suite of <strong>small, independent services</strong> that:</p><ul><li>Focus on a specific business capability</li><li>Are loosely coupled</li><li>Communicate via lightweight protocols like HTTP, gRPC, or message queues</li></ul><blockquote>See for more information: <a href="https://medium.com/@olehslabak/api-architecture-styles-overview-pros-cons-best-use-cases-a3be7e44e5f1">API Architecture Styles: Overview, Pros, Cons &amp; Best Use Cases</a></blockquote><ul><li>Can be developed, deployed, and scaled <strong>independently</strong></li></ul><h3>⚙️ Key Characteristics</h3><ul><li>Each service has its own <strong>codebase</strong> and <strong>database</strong></li><li>Built around <strong>business domains</strong> (Domain-Driven Design)</li><li>Supports <strong>polyglot programming</strong> (different languages per service)</li><li>Typically deployed in <strong>containers</strong> (e.g., Docker, Kubernetes)</li><li>Inter-service communication via APIs or message brokers (e.g., Kafka)</li></ul><h3>✅ Advantages</h3><ul><li>Independent <strong>deployment and scaling</strong></li><li>Better <strong>fault isolation</strong></li><li>Faster <strong>development cycles</strong></li><li>Enables <strong>technology diversity</strong></li><li>Aligns well with <strong>CI/CD pipelines</strong> and <strong>DevOps</strong></li></ul><h3>❌ Disadvantages</h3><ul><li><strong>Operational complexity</strong> (e.g., monitoring, service discovery, logging)</li><li>Harder to manage <strong>distributed transactions</strong></li><li>Increased <strong>network latency and debugging difficulty</strong></li><li><strong>Versioning</strong> and <strong>API contracts</strong> must be well-managed</li></ul><h3>🔄 When to Use</h3><ul><li>Large teams working on complex applications</li><li>Need for high availability, scalability, and modularity</li><li>Systems with <strong>frequent updates</strong> or <strong>domain complexity</strong></li><li>Cloud-native or containerized environments</li></ul><h3>💡 Real-World Examples</h3><ul><li>Netflix</li><li>Amazon</li><li>Uber</li><li>Spotify</li></ul><h3>🏗️ Monolithic Architecture vs 🧩 Microservices Architecture</h3><h3>Definition</h3><ul><li><strong>Monolithic:</strong><br> An application is built as a <strong>single, tightly-coupled unit</strong> where all components (UI, business logic, database access, etc.) are part of the same codebase and deployed together.</li><li><strong>Microservices:</strong><br> An application is composed of <strong>independent, loosely-coupled services</strong>, each focusing on a specific business function, and deployed independently.</li></ul><h3>Architecture Structure</h3><ul><li><strong>Monolithic:</strong> One executable or process.</li><li><strong>Microservices:</strong> Many small services, often communicating over network (HTTP, gRPC, etc.).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*a9ON9lTR19X6J0VIDCqxjA.png" /></figure><h3>Development</h3><ul><li><strong>Monolithic:</strong> Easier to build and manage for small teams and projects.</li><li><strong>Microservices:</strong> Supports <strong>parallel development</strong> across teams but requires <strong>more coordination</strong>.</li></ul><h3>Deployment</h3><ul><li><strong>Monolithic:</strong> Entire app must be rebuilt and redeployed for any change.</li><li><strong>Microservices:</strong> Individual services can be deployed independently.</li></ul><h3>Scalability</h3><ul><li><strong>Monolithic:</strong> Scaling is done by replicating the whole application (vertical or horizontal scaling).</li><li><strong>Microservices:</strong> Individual components can be scaled <strong>independently</strong>, optimizing resources.</li></ul><blockquote>More about <strong>Scalability: </strong><a href="https://medium.com/@olehslabak/system-design-key-concepts-8fa04c5d5119?source=your_stories_page--------------------------------------------">Core Principles of System Design: Scalability</a></blockquote><h3>Technology Stack</h3><ul><li><strong>Monolithic:</strong> Single stack (e.g., Java + MySQL).</li><li><strong>Microservices:</strong> Polyglot — different services can use different tech stacks (e.g., Node.js for auth, Go for payments).</li></ul><h3>Fault Isolation</h3><ul><li><strong>Monolithic:</strong> A failure in one module can bring down the whole application.</li><li><strong>Microservices:</strong> Failures are contained — one service going down doesn’t crash the others (if designed properly).</li></ul><blockquote>More about <strong>Fault Tolerance</strong> : <a href="https://medium.com/@olehslabak/core-principles-of-system-design-fault-tolerance-a807072bce51?source=your_stories_page--------------------------------------------">Core Principles of System Design: Fault Tolerance</a></blockquote><h3>Operational Complexity</h3><ul><li><strong>Monolithic:</strong> Simple to deploy and monitor.</li><li><strong>Microservices:</strong> Requires service discovery, distributed logging, tracing, monitoring, CI/CD pipelines, etc.</li></ul><h3>Testing</h3><ul><li><strong>Monolithic:</strong> Easier unit and integration testing due to tight coupling.</li><li><strong>Microservices:</strong> More difficult due to distributed nature — requires contract testing and service mocking.</li></ul><h3>Use Cases</h3><p><strong>Monolithic:</strong></p><ul><li>MVPs</li><li>Small to medium-size apps</li><li>Teams with limited DevOps capacity</li></ul><p><strong>Microservices:</strong></p><ul><li>Large-scale, evolving systems</li><li>Cloud-native, CI/CD heavy environments</li><li>Organizations practicing DevOps/SRE</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F3ud6d%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F3ud6d%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F3ud6d%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="946" height="439" frameborder="0" scrolling="no"><a href="https://medium.com/media/605caf6567b5fe518844c1b6efc2ca50/href">https://medium.com/media/605caf6567b5fe518844c1b6efc2ca50/href</a></iframe><h3>Useful links:</h3><p>Microservices architecture is a design approach where independent, loosely coupled services align with specific business functions, enabling flexible scaling and updates without affecting the whole system.</p><blockquote><a href="https://www.krasamo.com/microservices-architecture-for-real-world-business-needs/">Microservices Architecture for Solving Business Needs</a></blockquote><p>Design Patterns for Microservices Architecture : API Gateway Pattern, Service Registry Pattern, Circuit Breaker Pattern, Saga Pattern, Event Sourcing Pattern, etc.:</p><blockquote><a href="https://www.geeksforgeeks.org/system-design/microservices/">What are Microservices?</a></blockquote><p>8 Keys to Help You Get Started Use And Work With Microservices Architecture<em> </em>Today</p><blockquote><a href="https://medium.com/hashmapinc/the-what-why-and-how-of-a-microservices-architecture-4179579423a9"><em>“The What, Why, and How of a Microservices Architecture”</em> by Jetinder Singh on Medium</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vZXVwIve0gZ7BmCV" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a79ba8479ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Principles of System Design: Checksum]]></title>
            <link>https://olehslabak.medium.com/core-principles-of-system-design-checksum-34fcacfadc83?source=rss-850fc6e62b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/34fcacfadc83</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[checksums]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Oleh Slabak]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 08:54:54 GMT</pubDate>
            <atom:updated>2025-07-31T08:57:20.162Z</atom:updated>
            <content:encoded><![CDATA[<p>🧠A <strong>checksum</strong> is a small-sized, fixed-length piece of data derived from a larger block of input (e.g., a file, message, or packet).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ffb8uEfs65-nI3xq" /><figcaption>Photo by <a href="https://unsplash.com/@daveballew?utm_source=medium&amp;utm_medium=referral">David Ballew</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🧠 Core Idea in System Design</h3><p>In system design, a checksum helps ensure <strong>data integrity</strong> — that data hasn’t been corrupted while:</p><ul><li>Being transferred over a network (e.g. HTTP, TCP)</li><li>Being stored on disk (e.g. file systems, databases, caches)</li><li>Being replicated between systems (e.g. backup/restore, data sync)</li><li>Being received from external services (e.g. uploaded file, API payload)</li></ul><h3>🔧 How It Works</h3><ol><li>Sender generates a <strong>checksum</strong> of the original data using a checksum algorithm (e.g., CRC32, Adler-32, SHA-256).</li><li>The data and checksum are sent or stored together.</li><li>The receiver/system recomputes the checksum on the received data.</li><li>If the new checksum <strong>matches</strong> the original, the data is assumed to be intact.<br> If not — corruption is detected.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FsgmkY%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FsgmkY%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FsgmkY%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="990" height="474" frameborder="0" scrolling="no"><a href="https://medium.com/media/96d92700bab2eb95af4643efc12d4c41/href">https://medium.com/media/96d92700bab2eb95af4643efc12d4c41/href</a></iframe><h3>✅ When and Where to Use in System Design</h3><ul><li><strong>File uploads/downloads:</strong> Ensure file wasn’t corrupted.</li><li><strong>API payloads:</strong> Validate large JSON or binary content.</li><li><strong>Databases:</strong> Detect corruption in stored blocks.</li><li><strong>Distributed storage (e.g. S3, HDFS):</strong> Check integrity of replicas.</li><li><strong>Caching systems:</strong> Verify if cached data is stale or corrupted.</li><li><strong>Log shipping:</strong> Compare sender and receiver log chunks.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fb1VCc%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fb1VCc%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2Fb1VCc%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="1020" height="399" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d55ddedc05c69c065b5cced7a2780a7/href">https://medium.com/media/7d55ddedc05c69c065b5cced7a2780a7/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34fcacfadc83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Architectural Styles: Monolithic Architecture]]></title>
            <link>https://olehslabak.medium.com/system-architectural-styles-monolithic-architecture-02227d57ea0d?source=rss-850fc6e62b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/02227d57ea0d</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[monolithic-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Oleh Slabak]]></dc:creator>
            <pubDate>Fri, 11 Jul 2025 08:28:16 GMT</pubDate>
            <atom:updated>2025-07-11T08:28:16.619Z</atom:updated>
            <content:encoded><![CDATA[<p>🏢A <strong>Monolithic Architecture</strong> is a traditional software architecture style where an application is built as a <strong>single, unified, and tightly coupled codebase</strong>.<br> All components — user interface, business logic, data access, and integrations — reside together and are deployed as one executable or service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wVfqxx44SOzaPMxq" /><figcaption>Photo by <a href="https://unsplash.com/@alex_quezada?utm_source=medium&amp;utm_medium=referral">Alex Quezada</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>🔩 Characteristics</h3><ul><li>Single, large codebase.</li><li>All modules compiled, packaged, and deployed together.</li><li>Typically uses a shared database.</li><li>Components interact via in-process calls rather than over a network.</li><li>Simple to develop initially but difficult to scale independently.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*8u-HwkT5rshdDW0iMCqq7g.png" /></figure><h3>📠 Typical Example</h3><p>An e-commerce system where:</p><ul><li>Product catalog</li><li>Cart management</li><li>User authentication</li><li>Payment processing — are all bundled into one application and deployed as a single artifact.</li></ul><h3>🔎 Advantages</h3><p>✅ Simple to develop, test, and deploy initially.<br> ✅ Easier to maintain for small teams or simple applications.<br> ✅ No network overhead between modules.<br> ✅ Straightforward transaction management and logging.</p><h3>🔍 Disadvantages</h3><p>❌ Hard to scale individual components.<br> ❌ Large, complex codebases are difficult to manage as the app grows.<br> ❌ Risky deployments — a small change requires redeploying the entire system.<br> ❌ Tight coupling makes it hard to adopt new technologies or refactor parts of the system.</p><h3>📖 When to Use</h3><ul><li>Simple, early-stage applications.</li><li>MVPs (minimum viable products).</li><li>Small teams with tight deadlines.</li><li>Systems with no complex scaling or modularity requirements.</li></ul><blockquote>More details you may found here :</blockquote><blockquote><a href="https://medium.com/design-microservices-architecture-with-patterns/monolithic-architecture-is-still-worth-at-2021-98bfc112dc24">Monolithic Architecture Is Still Worth at 2021 ?</a></blockquote><blockquote><a href="https://www.geeksforgeeks.org/system-design/monolithic-architecture-system-design/">Monolithic Architecture — System Design</a></blockquote><blockquote><a href="https://medium.com/design-microservices-architecture-with-patterns/when-to-use-monolithic-architecture-57c0653e245e">When to use Monolithic Architecture</a></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2F6tR6N%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2F6tR6N%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2F6tR6N%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="944" height="385" frameborder="0" scrolling="no"><a href="https://medium.com/media/907f956a6705549d0db6c568d5faaa39/href">https://medium.com/media/907f956a6705549d0db6c568d5faaa39/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W5VqWWPqekePCxtX" /><figcaption>Photo by <a href="https://unsplash.com/@hdbernd?utm_source=medium&amp;utm_medium=referral">Bernd 📷 Dittrich</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02227d57ea0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Principles of System Design: Consistent Hashing]]></title>
            <link>https://olehslabak.medium.com/core-principles-of-system-design-consistent-hashing-491c3d16a87e?source=rss-850fc6e62b2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/491c3d16a87e</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[consistent-hashing]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Oleh Slabak]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 06:25:47 GMT</pubDate>
            <atom:updated>2025-07-10T06:25:47.025Z</atom:updated>
            <content:encoded><![CDATA[<p>💍A technique used in distributed systems to evenly distribute data (or load) across a dynamic set of servers/nodes, <strong>minimizing the number of remapped keys when nodes are added or removed</strong>.</p><p>It’s widely used in:</p><ul><li>Distributed caches (like Memcached)</li><li>Sharded databases</li><li>Load balancers</li><li>Distributed object stores (like Amazon Dynamo)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XbhZRTXp_Lp36EMz" /><figcaption>Photo by <a href="https://unsplash.com/@jon_hodl?utm_source=medium&amp;utm_medium=referral">Jon Hodl</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1️⃣ The Problem with Traditional Hashing</h3><p>In <strong>traditional hashing</strong>, a key is assigned to a node using a simple formula like:</p><pre>node = hash(key) % number_of_nodes</pre><p><strong>Problem:</strong></p><ul><li>When a node is added or removed, almost all keys need to be remapped.</li><li>This causes massive cache misses, load redistribution, and poor scalability.</li></ul><p><strong>Example:</strong><br> If you have 3 cache servers and add a 4th, the modulo changes from % 3 to % 4, reshuffling almost all keys.</p><h3>2️⃣ How Consistent Hashing Works</h3><p>Consistent Hashing organizes both <strong>keys and nodes</strong> in the same hash space (a circular “ring”).</p><p><strong>Steps:</strong></p><ol><li>Hash both the <strong>keys</strong> and the <strong>nodes</strong> into a numerical space (e.g., 0–²³²-1).</li><li>Place them on a virtual <strong>hash ring</strong> based on their hash values.</li><li>Each key is stored on the first node it encounters moving clockwise on the ring.</li><li>When nodes join or leave:</li></ol><ul><li>Only the keys affected by the immediate neighboring node change.</li><li>Other keys remain where they are.</li></ul><p>This drastically reduces the number of keys that need to be remapped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*-rP1GZ8mZPegZYoF.png" /><figcaption>img source: <a href="https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/architecture/archDataDistributeHashing.html">Consistent hashing</a></figcaption></figure><blockquote>More details, how it works in Cassandra DB here :</blockquote><blockquote>DataStax <a href="https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/architecture/archDataDistributeHashing.html">Consistent hashing</a></blockquote><blockquote><a href="https://medium.com/@arun.kumar.mohapatra/consistent-hashing-in-cassandra-ensuring-scalability-fault-tolerance-afb546fc5ac8">Consistent Hashing in Cassandra: Ensuring Scalability &amp; Fault Tolerance</a></blockquote><h3>3️⃣ Constructing the Hash Ring</h3><ul><li>Use a consistent hashing function (like MD5 or SHA-1) to assign positions to both keys and nodes in a 0–²³² ring.</li><li>Sort nodes by hash value.</li><li>A key’s home node is the <strong>first node clockwise</strong> after its hash value.</li></ul><p><strong>Example:</strong><br> If the hash values are:</p><pre>Nodes: N1 (5), N2 (18), N3 (30)<br>Keys: K1 (7), K2 (23)</pre><ul><li><strong>K1</strong> is assigned to <strong>N2</strong></li><li><strong>K2</strong> is assigned to <strong>N3</strong></li></ul><p>When <strong>N2</strong> is removed:</p><ul><li>Only keys between <strong>N1</strong> and <strong>N3</strong> need to be reassigned.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*UF4YaSBUbJU1gkx6.png" /><figcaption>img source: <a href="https://stackoverflow.com/questions/49762878/classic-cassandra-and-coordination">https://stackoverflow.com/questions/49762878/classic-cassandra-and-coordination</a></figcaption></figure><h3>4️⃣ Virtual Nodes</h3><p><strong>Problem:</strong><br> If the number of real nodes is small, hash distribution might be uneven.</p><p><strong>Solution: Virtual Nodes (VNodes)</strong></p><ul><li>Each physical node is represented by multiple virtual positions on the ring.</li><li>For example, node N1 can have positions at hash values 10, 20, 50, 80.</li><li>Keys are assigned to the nearest virtual node moving clockwise.</li></ul><p><strong>Benefits:</strong></p><ul><li>More even key distribution</li><li>Reduces the risk of uneven load across physical nodes</li><li>Simplifies adding and removing physical nodes without major remapping</li></ul><blockquote>More details about Virtual nodes in Cassandra you may found here:</blockquote><blockquote><a href="https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/architecture/archDataDistributeVnodesUsing.html">DataStax Cassandra Virtual nodes</a></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FmlYCo%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FmlYCo%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FmlYCo%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="1010" height="389" frameborder="0" scrolling="no"><a href="https://medium.com/media/acd646051a9b9d2f20628ed2cbcc10b6/href">https://medium.com/media/acd646051a9b9d2f20628ed2cbcc10b6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VAaUW6DSJcAuR8aM" /><figcaption>Photo by <a href="https://unsplash.com/@msmelaniesykes?utm_source=medium&amp;utm_medium=referral">Melanie Sykes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=491c3d16a87e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>