<?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 OmidReza Salari on Medium]]></title>
        <description><![CDATA[Stories by OmidReza Salari on Medium]]></description>
        <link>https://medium.com/@Omid_dev?source=rss-f235a6f0aa95------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ASOVnkaLHRVcFe0AFeU19w.png</url>
            <title>Stories by OmidReza Salari on Medium</title>
            <link>https://medium.com/@Omid_dev?source=rss-f235a6f0aa95------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:59:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Omid_dev/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[Scatter and Gather Pattern in Distributed Architecture]]></title>
            <link>https://medium.com/@Omid_dev/scatter-and-gather-pattern-in-distributed-architecture-c63cda05e7bb?source=rss-f235a6f0aa95------2</link>
            <guid isPermaLink="false">https://medium.com/p/c63cda05e7bb</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[distributed-architecture]]></category>
            <category><![CDATA[cloud-native-application]]></category>
            <dc:creator><![CDATA[OmidReza Salari]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 11:00:04 GMT</pubDate>
            <atom:updated>2025-08-28T11:02:17.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VhHODUZgFVM8os2it2sjqw.png" /></figure><p>In distributed systems, one common challenge is <strong>querying multiple services efficiently</strong> and combining their results. The <strong>Scatter and Gather pattern</strong> solves this by:</p><ul><li><strong>Scatter</strong>: breaking a request into smaller sub-requests and sending them out to multiple services in parallel.</li><li><strong>Gather</strong>: collecting all the responses, merging them, and sending one unified result back to the client.</li></ul><h3>Real-World Analogy</h3><p>Imagine a teacher who needs a summary of a long book:</p><ul><li>Instead of one student reading the whole book, the teacher assigns <strong>different chapters to different students</strong> (scatter).</li><li>Each student summarizes their chapter.</li><li>The teacher <strong>collects all the summaries</strong> and combines them into one full report (gather).</li></ul><p>The work is finished much faster compared to one student doing everything alone.</p><h3>Example in Software</h3><p>Let’s say you’re building a <strong>travel aggregator app</strong>.</p><p>A user searches for flights from <strong>Helsinki (HEL) to Berlin (BER) on Sept 2</strong>.</p><p><strong>1. Scatter</strong>: The app sends the query simultaneously to several airline APIs:</p><ul><li>Lufthansa API</li><li>Finnair API</li><li>Ryanair API</li></ul><p><strong>2. Gather</strong>:</p><ul><li>Each airline API returns available flights and prices.</li><li>The aggregator collects all responses.</li><li>It normalizes the data (since each airline formats results differently).</li><li>It sorts flights by price or travel time.</li><li>Finally, it shows the user a <strong>single combined list of flights</strong>.</li></ul><h3>Where It’s Used</h3><ul><li><strong>Search engines</strong> → query multiple index shards, then merge results.</li><li><strong>Dashboards</strong> → pull data from orders, inventory, and customer services simultaneously.</li><li><strong>Recommendation systems</strong> → run multiple models in parallel, then combine their suggestions.</li><li><strong>Analytics</strong> → query multiple data partitions, then aggregate.</li></ul><h3>Benefits</h3><p>✅ Faster responses (parallel queries)<br> ✅ Scalability (just add more workers or services)<br> ✅ Can degrade gracefully (return partial results if some fail)</p><h3>Challenges</h3><p>⚠️ Some services might be slow → system needs timeouts.<br> ⚠️ Some services might fail → need fallback or partial results.<br> ⚠️ Data may come in different shapes → normalization is required.</p><h3>Final Thought</h3><p>The <strong>Scatter and Gather pattern</strong> is like <strong>teamwork</strong>: instead of one worker doing everything, many do small parts in parallel, and their efforts are combined.</p><p>It’s a simple yet powerful strategy behind <strong>search engines, travel sites, dashboards, and recommendation platforms</strong> — all systems where speed and scale matter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c63cda05e7bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chapter 3: A Framework for System Design Interviews]]></title>
            <link>https://medium.com/@Omid_dev/chapter-3-a-framework-for-system-design-interviews-5c88aca562ca?source=rss-f235a6f0aa95------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c88aca562ca</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[OmidReza Salari]]></dc:creator>
            <pubDate>Thu, 19 Dec 2024 10:05:05 GMT</pubDate>
            <atom:updated>2024-12-19T10:06:37.250Z</atom:updated>
            <content:encoded><![CDATA[<p>System design interviews can be daunting, requiring candidates to demonstrate both <strong>technical knowledge</strong> and<strong> problem-solving skills</strong>. Chapter 3 of the <em>System Design Interview</em> book introduces a structured framework that breaks down the process into manageable steps, ensuring that candidates approach system design methodically and confidently. In this article, we’ll explore this framework step-by-step, offering insights into its application.</p><h3>1. Understand the Problem</h3><p>The first step in any system design interview is to understand the problem statement thoroughly. Ask clarifying questions to define:</p><ul><li><strong>Scope</strong>: What is the system expected to do? Are there any explicit constraints?</li><li><strong>Users</strong>: Who are the primary users, and what are their needs?</li><li><strong>Scale</strong>: What scale is the system expected to handle?</li><li><strong>Features</strong>: What are the core features required?</li></ul><p><strong>Example questions:</strong></p><ul><li>Should this system support real-time interactions?</li><li>How many users are expected daily?</li><li>Are there specific performance requirements?</li></ul><p>Taking time to understand the problem avoids misaligned assumptions and sets a clear direction for the design.</p><h3>2. Establish Key Goals</h3><p>Once you’ve clarified the problem, outline the key goals and priorities. These could include:</p><ul><li><strong>Scalability</strong>: Ensuring the system can handle growth.</li><li><strong>Availability</strong>: Minimizing downtime and ensuring reliability.</li><li><strong>Latency</strong>: Reducing response times.</li><li><strong>Consistency</strong>: Maintaining data accuracy and integrity.</li></ul><p>Discussing trade-offs at this stage is crucial. For instance, would the system prioritize availability over consistency in case of network partitions?</p><h3>3. Design High-Level Architecture</h3><p>Next, propose a high-level architecture that outlines how the system’s components interact. This should include:</p><ul><li><strong>Clients</strong>: How users interact with the system (e.g., web or mobile apps).</li><li><strong>APIs</strong>: Communication between front-end and back-end.</li><li><strong>Back-End Services</strong>: Core logic and data processing.</li><li><strong>Data Storage</strong>: Where and how data is stored.</li></ul><p>Visual aids like diagrams are invaluable here. Start with a simple design and iterate based on feedback.</p><h3>4. Define Data Flow</h3><p>Understanding how data moves through the system is essential for identifying <strong>bottlenecks</strong> and <strong>ensuring efficiency</strong>. Consider:</p><ul><li>How requests are processed from clients to the back-end.</li><li>How data is stored, retrieved, and updated.</li><li>Any caching mechanisms to reduce database load.</li></ul><h3>5. Plan for Scalability</h3><p><strong>Scale</strong> is often a key concern in system design interviews. Address how your system will handle increased load by:</p><ul><li>Using load balancers to distribute traffic.</li><li>Employing replication and sharding for databases.</li><li>Implementing horizontal scaling to add servers.</li></ul><p>Mention real-world practices such as CDN usage for serving static assets or asynchronous processing with message queues.</p><h3>6. Address Specific Design Challenges</h3><p>Every system has unique challenges. Dive into areas like:</p><ul><li><strong>Data Partitioning</strong>: How will you partition data for scalability and efficiency?</li><li><strong>Consistency and Availability</strong>: How will your system balance the CAP theorem constraints?</li><li><strong>Security</strong>: How will you secure user data and prevent unauthorized access?</li></ul><h3>7. Discuss Trade-Offs and Alternatives</h3><p>System design involves balancing trade-offs. For example:</p><ul><li>Choosing between SQL and NoSQL databases.</li><li>Deciding on synchronous vs. asynchronous communication.</li><li>Prioritizing cost-efficiency vs. performance.</li></ul><p>Articulating these decisions shows your ability to think critically and holistically.</p><h3>8. Conclude with Future Enhancements</h3><p>Wrap up your design by discussing potential future improvements. For instance:</p><ul><li>Adding new features as user needs evolve.</li><li>Optimizing for cost as the system scales.</li><li>Conducting regular performance and security audits.</li></ul><p>This forward-thinking approach highlights your strategic vision.</p><h3>Practical Tips for Using the Framework</h3><ul><li><strong>Time Management</strong>: Allocate your time wisely to cover all aspects.</li><li><strong>Collaboration</strong>: Engage with the interviewer by asking for feedback and iterating on your design.</li><li><strong>Clarity</strong>: Use clear and concise language to explain your choices.</li></ul><p>By applying this framework, you’ll be able to systematically tackle any system design interview, showcasing both your technical skills and your ability to think strategically. Mastering these steps will set you apart and leave a lasting impression.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c88aca562ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Scalable Systems: Key Insights from Chapter 2 of System Design Interview]]></title>
            <link>https://medium.com/@Omid_dev/building-scalable-systems-key-insights-from-chapter-2-of-system-design-interview-5ba73e69f23f?source=rss-f235a6f0aa95------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ba73e69f23f</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[OmidReza Salari]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 21:20:07 GMT</pubDate>
            <atom:updated>2024-10-30T21:54:32.137Z</atom:updated>
            <content:encoded><![CDATA[<p>Chapter 2 of <em>System Design Interview</em> by Alex Xu offers a deep dive into scalability fundamentals, ideal for aspiring system architects and developers preparing for high-level interviews. Here, we’ll explore the foundational concepts that make scalable systems possible.</p><h4>1. Load Balancing: Distributing the Load</h4><p>Imagine a website that millions of users want to access at once. If all requests were directed to a single server, it would quickly become overwhelmed, leading to delays and crashes. <strong>Load balancing</strong> solves this by distributing incoming requests across multiple servers. By managing traffic this way, systems can handle more requests seamlessly.</p><p><strong>Key Strategies:</strong></p><ul><li><strong>Horizontal vs. Vertical Scaling</strong>: Horizontal scaling adds more servers to the system, whereas vertical scaling increases the resources of a single server. Horizontal scaling is typically more scalable and resilient.</li><li><strong>Statelessness</strong>: Keeping servers stateless allows requests to be handled independently by any server, making load balancing more effective and less dependent on individual server status.</li></ul><h4>2. Data Partitioning: Managing Data Growth with Sharding</h4><p>As data grows, storing it all in a single database creates a bottleneck. <strong>Data partitioning</strong> often called <strong>sharding</strong> — breaks data into smaller segments, making it easier to manage, query, and scale.</p><p><strong>Types of Partitioning:</strong></p><ul><li><strong>Horizontal Partitioning</strong>: Splitting rows across multiple databases, so each database has a subset of the data.</li><li><strong>Vertical Partitioning</strong>: Dividing columns by specific data categories, so each database contains only relevant fields.</li></ul><p>Data partitioning allows systems to store and process vast amounts of information more efficiently. For example, a social media platform might <strong>shard</strong> users by geographic location to speed up data access and reduce database load.</p><h4>3. Caching: Speeding Up Access to Frequent Requests</h4><p><strong>Caching</strong> is like a <strong>temporary</strong> storage room for frequently accessed data. By keeping commonly requested information readily available, caching can drastically reduce response times and relieve backend servers.</p><p><strong>Types of Caching:</strong></p><ul><li><strong>Client-Side Caching</strong>: Storing data on the user’s device. This is commonly used in web browsers to load pages faster.</li><li><strong>Server-Side Caching</strong>: Storing data on the server side for quicker access. This might include caching user data or product details in e-commerce platforms.</li></ul><p><strong>By caching, we avoid frequent database access for repeated requests, creating a smoother experience for users.</strong></p><h4>4. Asynchronous Processing: Decoupling Tasks for Efficiency</h4><p>Not all processes need immediate completion. <strong>Asynchronous processing</strong> enables systems to handle resource-intensive tasks in the background, improving overall efficiency and responsiveness.</p><p><strong>Key Components:</strong></p><ul><li><strong>Message Queues</strong>: These hold tasks in a <strong>queue</strong> until they can be processed, helping prevent <strong>bottlenecks</strong>. If an e-commerce site processes payment confirmations asynchronously, it allows the user to proceed without waiting for a server to finish processing.</li><li><strong>Event-Driven Systems</strong>: Rather than constantly polling to check for updates, an event-driven system reacts when a specific <strong>event</strong> occurs. This allows systems to operate more efficiently and saves resources.</li></ul><h4>5. Rate Limiting and Throttling: Managing Overuse</h4><p>To prevent abuse or accidental server overload, systems enforce <strong>rate limiting</strong>, restricting the number of requests a user or application can make over a certain time. This is especially important for public APIs, which need to balance accessibility with server integrity.</p><p><strong>Common Strategies:</strong></p><ul><li><strong>User-Based Rate Limiting</strong>: Setting request limits per user. For instance, a streaming service might limit downloads to protect the network from overuse.</li><li><strong>Global Rate Limiting</strong>: Setting an overall threshold to safeguard server performance. This can prevent an influx of traffic from overwhelming the system.</li></ul><p>These techniques help systems remain responsive under heavy load, avoiding service interruptions.</p><h3>Real-World Applications: How Industry Giants Scale</h3><p><strong>Netflix’s Load Balancing</strong>: Netflix manages a massive audience by distributing requests across multiple servers, ensuring smooth streaming worldwide. Using both <strong>horizontal scaling and stateless services</strong>, they keep servers responsive and resilient.</p><p><strong>Amazon’s Caching</strong>: Amazon employs caching to ensure customers experience fast, reliable page loads. By caching product information and user data, Amazon enhances the shopping experience while reducing server load.</p><h3>Conclusion: Building for Growth and Reliability</h3><p>Scalability isn’t just about handling millions of users; it’s about crafting systems that remain <strong>reliable</strong>, <strong>efficient</strong>, and <strong>responsive under pressure</strong>. By implementing these principles from Chapter 2 of <em>System Design Interview</em>, you’ll be well-equipped to design systems that can handle the demands of today’s digital world.</p><p>For developers, architects, and interviewees, these concepts are essential, not only to keep up with high-demand environments but also to build platforms ready for continuous growth.</p><p>By exploring <strong>load balancing</strong>, <strong>sharding</strong>, <strong>caching</strong>, <strong>asynchronous processing</strong>, and<strong> rate limiting</strong>, this chapter offers invaluable lessons that extend far beyond the interview room.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ba73e69f23f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding System Design: A Breakdown of Chapter 1 of System Design Interview]]></title>
            <link>https://medium.com/@Omid_dev/understanding-system-design-a-breakdown-of-chapter-1-of-system-design-interview-f6f6f81939f5?source=rss-f235a6f0aa95------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6f6f81939f5</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[OmidReza Salari]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 16:49:21 GMT</pubDate>
            <atom:updated>2024-09-23T19:39:03.118Z</atom:updated>
            <content:encoded><![CDATA[<p>System design interviews have become a critical part of technical hiring processes at major tech companies. Whether you’re preparing for an interview or simply aiming to deepen your understanding of scalable systems, the<strong> <em>System Design Interview</em></strong> by <strong>Alex Xu</strong> is a valuable resource. In this article, we’ll break down <strong>Chapter 1</strong> of the book and explore its key insights to help you build a strong foundation for system design.</p><h3>Key Concepts in System Design</h3><p>Before diving into specific system architectures, Chapter 1 highlights several important system design fundamentals:</p><ol><li><strong>Scalability:</strong> How well a system can handle increasing loads without degrading performance.</li><li><strong>Availability:</strong> The ability of the system to remain operational despite failures.</li><li><strong>Reliability:</strong> Ensuring the system performs as expected over time.</li><li><strong>Maintainability:</strong> How easily the system can be updated, debugged, and adapted to new requirements.</li><li><strong>Performance:</strong> How efficiently the system processes requests and delivers responses</li></ol><p>Understanding these concepts helps guide the <strong>decision-making process</strong> when designing any system, from small-scale applications to large distributed systems.</p><h3>The Process of System Design</h3><h3>1. Clarifying Requirements</h3><p>The first step in system design is <strong>understanding the problem</strong> <strong>you’re solving.</strong> Chapter 1 stresses the importance of asking clarifying questions to make sure you fully grasp the requirements. This is where many candidates go wrong in system design interviews — they jump into solutions without fully understanding what the system needs to accomplish.</p><p>In a real-world scenario, product requirements can be vague. It’s essential to dig deeper, asking questions like:</p><ul><li>How many users are expected to use the system?</li><li>What’s the expected read-to-write ratio?</li><li>Is there a latency requirement for the system?</li></ul><p>By understanding these details, you can tailor your system to the specific needs of the application.</p><h3>2. Defining Key Components</h3><p>Once you have a solid grasp of the requirements, the next step is to<strong> identify the major components of your system</strong>. Chapter 1 introduces some common system components:</p><ul><li><strong>Load Balancer:</strong> Distributes incoming traffic across multiple servers to prevent any one server from becoming overwhelmed.</li><li><strong>Application Server:</strong> Handles business logic and processes requests.</li><li><strong>Database:</strong> Stores data, often divided into relational databases (SQL) or NoSQL databases depending on the use case.</li></ul><p>These are the building blocks of many scalable systems. As you move forward in system design, understanding how these components interact is crucial.</p><h3>3. Designing for Scalability</h3><p>Chapter 1 emphasizes that scalability is one of the most important considerations in system design. Whether you’re working on a small startup or a global application,<strong> the ability to scale efficiently can determine the success of your system.</strong></p><p>To scale effectively, you need to consider both <strong>vertical scaling </strong>(increasing the capacity of individual machines) and <strong>horizontal scaling</strong> (adding more machines to distribute the load). Most modern systems favor horizontal scaling because it allows for <strong>better fault tolerance</strong> and is generally more <strong>cost-effective.</strong></p><h3>4. Data Partitioning and Replication</h3><p>As systems grow, a single database may not be sufficient to handle all of the read and write requests. This is where concepts like <strong>data partitioning</strong> and <strong>replication</strong> come into play:</p><ul><li><strong>Partitioning</strong> involves breaking a large dataset into smaller, more manageable pieces.</li><li><strong>Replication</strong> ensures that copies of data are stored across different machines to improve availability and fault tolerance.</li></ul><p>These techniques are particularly useful when building distributed systems and are foundational concepts that will be explored in more detail throughout the book.</p><h3>Preparing for System Design Interviews</h3><p>Chapter 1 of <em>System Design Interview</em> also provides tips on preparing for system design interviews, which are often open-ended and <strong>designed to test your ability to think critically about large-scale systems.</strong> Here are a few steps to keep in mind:</p><ol><li><strong>Ask clarifying questions:</strong> Never assume you know all the requirements. Clarify things like user load, traffic patterns, and performance needs.</li><li><strong>Outline a high-level design:</strong> Don’t dive too deep into details right away. Start with a rough architecture that meets the core requirements.</li><li><strong>Discuss trade-offs:</strong> There is no perfect system. Every decision you make will have trade-offs in terms of performance, cost, and complexity. Be prepared to explain your choices.</li></ol><h3>Conclusion</h3><p>Chapter 1 of <em>System Design Interview</em> sets the stage for a thorough exploration of how to design <strong>scalable</strong>, <strong>reliable</strong>, and <strong><em>maintainable</em></strong> systems. It’s an essential foundation that covers the high-level concepts you’ll need to understand as you dive deeper into system design. Whether you’re preparing for an interview or looking to improve your system architecture skills, mastering the principles in this chapter is a critical first step.</p><p>Stay tuned for more insights as we continue to break down subsequent chapters in future articles ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6f6f81939f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka: A Comprehensive Guide with PHP Examples]]></title>
            <link>https://medium.com/@Omid_dev/apache-kafka-a-comprehensive-guide-with-php-examples-4cf6a6491666?source=rss-f235a6f0aa95------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cf6a6491666</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[OmidReza Salari]]></dc:creator>
            <pubDate>Mon, 01 Jul 2024 09:12:23 GMT</pubDate>
            <atom:updated>2024-07-01T09:12:23.660Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache Kafka, an open-source stream-processing software platform, has revolutionized how real-time data is managed and processed. Originally developed by <strong>LinkedIn</strong> and now a part of the Apache Software Foundation, Kafka is designed to handle high throughput, fault tolerance, and horizontal scalability. In this article, we’ll dive deep into Kafka’s architecture, its core concepts, and demonstrate how to integrate Kafka with PHP.</p><h3>Table of Contents</h3><ol><li>Introduction to Kafka</li><li>Core Concepts of Kafka</li><li>Kafka Architecture</li><li>Installing Kafka</li><li>Setting Up Kafka with PHP</li><li>Producing Messages to Kafka in PHP</li><li>Consuming Messages from Kafka in PHP</li><li>Conclusion</li></ol><h3>1. Introduction to Kafka</h3><p>Apache Kafka is a distributed event streaming platform capable of handling trillions of events a day. It is used for building real-time data pipelines and streaming applications. Kafka’s robust architecture makes it suitable for a variety of use cases, including log aggregation, stream processing, event sourcing, and real-time analytics.</p><h3>2. Core Concepts of Kafka</h3><p>Before diving into the technical setup, let’s understand some core concepts:</p><ul><li><strong>Producer</strong>: An application that sends messages to Kafka.</li><li><strong>Consumer</strong>: An application that reads messages from Kafka.</li><li><strong>Topic</strong>: A category or feed name to which records are stored and published.</li><li><strong>Partition</strong>: A topic is divided into partitions to allow for parallel processing.</li><li><strong>Broker</strong>: A Kafka server that stores data and serves clients.</li><li><strong>Consumer Group</strong>: A group of consumers that work together to consume messages from a topic.</li></ul><h3>3. Kafka Architecture</h3><p>Kafka’s architecture consists of the following key components:</p><ul><li><strong>Kafka Cluster</strong>: A cluster of multiple brokers.</li><li><strong>ZooKeeper</strong>: Used to manage and coordinate the Kafka brokers.</li><li><strong>Producers and Consumers</strong>: Applications that produce and consume messages, respectively.</li></ul><p>Each topic in Kafka is divided into partitions, and each partition is replicated across multiple brokers for fault tolerance. This ensures that Kafka can handle large volumes of data with high reliability and availability.</p><h3>4. Installing Kafka</h3><p>To get started with Kafka, you need to install Kafka and ZooKeeper. Here’s a brief guide:</p><h4>Step 1: Download Kafka</h4><p>Download the latest version of Kafka from the <a href="https://kafka.apache.org/downloads">official Apache Kafka website</a>.</p><h4>Step 2: Extract and Configure Kafka</h4><pre>tar -xzf kafka_2.13-2.8.0.tgz<br>cd kafka_2.13-2.8.0</pre><h4>Step 3: Start ZooKeeper</h4><p>Kafka requires ZooKeeper to be running. Start ZooKeeper using the following command:</p><pre>bin/zookeeper-server-start.sh config/zookeeper.properties</pre><h4>Step 4: Start Kafka Broker</h4><p>Start the Kafka broker using the following command:</p><pre>bin/kafka-server-start.sh config/server.properties</pre><h3>5. Setting Up Kafka with PHP</h3><p>To integrate Kafka with PHP, we’ll use the <a href="https://github.com/arnaud-lb/php-rdkafka">php-rdkafka</a> extension, which is a PHP binding for librdkafka.</p><h4>Step 1: Install librdkafka</h4><p>Before installing the PHP extension, you need to install librdkafka. On Ubuntu, you can use the following command:</p><pre>sudo apt-get install librdkafka-dev</pre><h4>Step 2: Install php-rdkafka</h4><p>Install the php-rdkafka extension using PECL:</p><pre>pecl install rdkafka</pre><p>Add the extension to your php.ini file:</p><pre>extension=rdkafka.so</pre><h3>6. Producing Messages to Kafka in PHP</h3><p>Here’s a simple example of a PHP producer that sends messages to a Kafka topic:</p><pre>&lt;?php<br>$conf = new RdKafka\Conf();<br>$conf-&gt;set(&#39;metadata.broker.list&#39;, &#39;localhost:9092&#39;);<br><br>$producer = new RdKafka\Producer($conf);<br>$topic = $producer-&gt;newTopic(&#39;test_topic&#39;);<br><br>for ($i = 0; $i &lt; 10; $i++) {<br>    $topic-&gt;produce(RD_KAFKA_PARTITION_UA, 0, &quot;Message $i&quot;);<br>    $producer-&gt;poll(0);<br>}<br><br>while ($producer-&gt;getOutQLen() &gt; 0) {<br>    $producer-&gt;poll(50);<br>}<br><br>echo &quot;Messages produced successfully!&quot;;<br>?&gt;</pre><p>This script configures a producer, sets the broker list, and sends ten messages to the test_topic topic.</p><h3>7. Consuming Messages from Kafka in PHP</h3><p>Here’s how you can consume messages from a Kafka topic using PHP:</p><pre>&lt;?php<br>$conf = new RdKafka\Conf();<br>$conf-&gt;set(&#39;group.id&#39;, &#39;myConsumerGroup&#39;);<br><br>$consumer = new RdKafka\KafkaConsumer($conf);<br>$consumer-&gt;subscribe([&#39;test_topic&#39;]);<br><br>echo &quot;Waiting for messages...\n&quot;;<br><br>while (true) {<br>    $message = $consumer-&gt;consume(120*1000);<br>    switch ($message-&gt;err) {<br>        case RD_KAFKA_RESP_ERR_NO_ERROR:<br>            echo &quot;Received message: &quot; . $message-&gt;payload . &quot;\n&quot;;<br>            break;<br>        case RD_KAFKA_RESP_ERR__PARTITION_EOF:<br>            echo &quot;No more messages; will wait for more\n&quot;;<br>            break;<br>        case RD_KAFKA_RESP_ERR__TIMED_OUT:<br>            echo &quot;Timed out\n&quot;;<br>            break;<br>        default:<br>            throw new \Exception($message-&gt;errstr(), $message-&gt;err);<br>            break;<br>    }<br>}<br>?&gt;</pre><p>This consumer script subscribes to the test_topic topic and continuously listens for new messages, processing them as they arrive.</p><h3>8. Conclusion</h3><p>Apache Kafka is a powerful tool for real-time data streaming and processing. Integrating Kafka with PHP is straightforward with the php-rdkafka extension, allowing PHP applications to produce and consume messages efficiently. With its scalable and fault-tolerant architecture, Kafka is an excellent choice for building robust data pipelines and streaming applications.</p><p>Whether you’re dealing with log aggregation, real-time analytics, or event sourcing, Kafka’s capabilities can significantly enhance your application’s performance and reliability. By following the examples and guidelines provided in this article, you can start leveraging the power of Kafka in your PHP projects today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cf6a6491666" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to gRPC: Building a Golang Server and a PHP Client]]></title>
            <link>https://medium.com/@Omid_dev/introduction-to-grpc-building-a-golang-server-and-a-php-client-c73c9511964f?source=rss-f235a6f0aa95------2</link>
            <guid isPermaLink="false">https://medium.com/p/c73c9511964f</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[rpc]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[OmidReza Salari]]></dc:creator>
            <pubDate>Wed, 12 Jun 2024 10:27:38 GMT</pubDate>
            <atom:updated>2024-06-12T10:27:38.034Z</atom:updated>
            <content:encoded><![CDATA[<p>GRPC has emerged as a powerful tool for building distributed systems and microservices in recent years. It offers a high-performance, language-agnostic framework for defining and consuming APIs. In this article, we will explore the basics of gRPC, and walk through a practical example of implementing a gRPC server in Golang and a client in PHP.</p><h3>What is gRPC?</h3><p>gRPC (gRPC Remote Procedure Calls) is an open-source framework developed by <strong>Google</strong>. It leverages <strong>HTTP/2</strong> for transport, Protocol Buffers (protobuf) as the interface definition language, and offers features such as authentication, load balancing, and more.</p><p>Key benefits of gRPC include:</p><ul><li><strong>Efficient serialization</strong>: Using Protocol Buffers, gRPC allows for efficient and compact data serialization.</li><li><strong>Language interoperability</strong>: gRPC supports multiple programming languages, making it ideal for polyglot environments.</li><li><strong>Bi-directional streaming</strong>: gRPC supports various types of RPC, including unary, server streaming, client streaming, and bi-directional streaming.</li></ul><h3>Setting Up a gRPC Server in Golang</h3><p>Let’s start by setting up a gRPC server using Golang. We will create a simple service that allows clients to perform basic operations like saying hello.</p><h4>Step 1: Install Prerequisites</h4><p>Before we begin, make sure you have Go installed. You can download it from the <a href="https://golang.org/dl/">official site</a>. Additionally, you will need protoc, the Protocol Buffers compiler, and the gRPC plugin for Go.</p><pre># Install protoc<br>brew install protobuf<br><br># Install protoc-gen-go and protoc-gen-go-grpc<br>go install google.golang.org/protobuf/cmd/protoc-gen-go@latest<br>go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest</pre><h4>Step 2: Define the Protocol Buffers File</h4><p>Create a directory for your project and define a .proto file.</p><pre>// hello.proto<br>syntax = &quot;proto3&quot;;<br><br>package hello;<br><br>service HelloService {<br>  rpc SayHello (HelloRequest) returns (HelloResponse);<br>}<br><br>message HelloRequest {<br>  string name = 1;<br>}<br><br>message HelloResponse {<br>  string message = 1;<br>}</pre><h4>Step 3: Generate Go Code from the .proto File</h4><p>Use protoc to generate Go code from the .proto file.</p><pre>protoc --go_out=. --go-grpc_out=. hello.proto</pre><h4>Step 4: Implement the gRPC Server</h4><p>Now, let’s implement the gRPC server in Go.</p><pre>// server/main.go<br>package main<br><br>import (<br> &quot;context&quot;<br> &quot;log&quot;<br> &quot;net&quot;<br><br> &quot;google.golang.org/grpc&quot;<br> pb &quot;path/to/your/proto/package&quot; // Import the generated protobuf code <br>)<br><br>type server struct {<br> pb.UnimplementedHelloServiceServer<br>}<br><br>func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {<br> message := &quot;Hello, &quot; + req.GetName()<br> return &amp;pb.HelloResponse{Message: message}, nil<br>}<br><br>func main() {<br> lis, err := net.Listen(&quot;tcp&quot;, &quot;:50051&quot;)<br> if err != nil {<br>  log.Fatalf(&quot;failed to listen: %v&quot;, err)<br> }<br><br> s := grpc.NewServer()<br> pb.RegisterHelloServiceServer(s, &amp;server{})<br><br> log.Printf(&quot;server listening at %v&quot;, lis.Addr())<br> if err := s.Serve(lis); err != nil {<br>  log.Fatalf(&quot;failed to serve: %v&quot;, err)<br> }<br>}</pre><h3>Setting Up a gRPC Client in PHP</h3><p>Next, we’ll set up a gRPC client in PHP to interact with our Go server.</p><h4>Step 1: Install Prerequisites</h4><p>Ensure you have PHP installed on your system. You will also need Composer, the PHP package manager, and the gRPC PHP extension.</p><pre># Install Composer<br>php -r &quot;copy(&#39;https://getcomposer.org/installer&#39;, &#39;composer-setup.php&#39;);&quot;<br>php composer-setup.php<br>php -r &quot;unlink(&#39;composer-setup.php&#39;);&quot;<br><br># Install gRPC PHP extension<br>pecl install grpc<br><br># Install protobuf PHP extension<br>pecl install protobuf</pre><h4>Step 2: Install gRPC PHP Library</h4><p>Use Composer to install the gRPC PHP library.</p><pre>composer require grpc/grpc google/protobuf</pre><h4>Step 3: Generate PHP Code from the .proto File</h4><p>It would help if you generated PHP classes from the .proto file. This requires the protoc compiler with the grpc_php_plugin.</p><pre>protoc --php_out=./ --grpc_out=./ --plugin=protoc-gen-grpc=grpc_php_plugin hello.proto</pre><h4>Step 4: Implement the PHP Client</h4><p>Finally, create a PHP script to act as the gRPC client.</p><pre>// client.php<br>require &#39;vendor/autoload.php&#39;;<br>require &#39;GPBMetadata/Hello.php&#39;;<br>require &#39;Hello/HelloServiceClient.php&#39;;<br>require &#39;Hello/Hello.pb.php&#39;;<br><br>use Hello\HelloServiceClient;<br>use Hello\HelloRequest;<br><br>$client = new HelloServiceClient(&#39;localhost:50051&#39;, [<br>    &#39;credentials&#39; =&gt; \Grpc\ChannelCredentials::createInsecure(),<br>]);<br><br>$request = new HelloRequest();<br>$request-&gt;setName(&#39;World&#39;);<br><br>list($response, $status) = $client-&gt;SayHello($request)-&gt;wait();<br><br>if ($status-&gt;code !== \Grpc\STATUS_OK) {<br>    echo &quot;Error: &quot; . $status-&gt;details . PHP_EOL;<br>} else {<br>    echo &quot;Greeting: &quot; . $response-&gt;getMessage() . PHP_EOL;<br>}</pre><h3>Running the Example</h3><ol><li>Start the gRPC server:</li></ol><pre>go run server/main.go</pre><p>2. Run the PHP client:</p><pre>php client.php</pre><p>You should see the following output:</p><pre>Greeting: Hello, World</pre><p><strong>Conclusion</strong></p><p>In this article, we have introduced gRPC and demonstrated how to set up a simple gRPC server in Golang and a client in PHP. gRPC’s efficiency and language interoperability make it an excellent choice for building scalable, high-performance APIs in polyglot environments. With this foundation, you can extend your services to include more complex logic and explore additional gRPC features such as streaming and authentication.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c73c9511964f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Mock, Dummy, Spy, Stub, and Fake in PHP Unit Testing]]></title>
            <link>https://medium.com/@Omid_dev/understanding-mock-dummy-spy-stub-and-fake-in-php-unit-testing-b8c03b323d0e?source=rss-f235a6f0aa95------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8c03b323d0e</guid>
            <category><![CDATA[test-doubles]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[OmidReza Salari]]></dc:creator>
            <pubDate>Wed, 29 May 2024 09:42:55 GMT</pubDate>
            <atom:updated>2024-05-29T10:38:25.955Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of unit testing, particularly in PHP, various types of test doubles are used to simulate the behavior of complex objects. These test doubles include mocks, dummies, spies, stubs, and fakes. Understanding the differences between these terms and their appropriate use cases is crucial for writing effective tests. In this article, we will explore each of these concepts with practical PHP examples.</p><h3>Mock</h3><p>A mock is an object that is pre-programmed with expectations which form a specification of the calls they are expected to receive. Mocks are typically used to verify that certain interactions took place.</p><p><strong>Example in PHP:</strong></p><pre>// Create a mock object for the Cache class<br>$cacheMock = $this-&gt;getMockBuilder(Cache::class)-&gt;getMock();<br><br>// Set expectation for the &#39;get&#39; method to be called once and return a specific result<br>$cacheMock-&gt;expects($this-&gt;once())<br> -&gt;method(&#39;get&#39;)<br> -&gt;with(&#39;key&#39;)<br> -&gt;willReturn([&#39;result&#39; =&gt; &#39;fake_result&#39;]);</pre><h3>Dummy</h3><p>A dummy is an object that is passed around but never actually used. It is usually just a placeholder to fill parameter lists.</p><p><strong>Example in PHP:</strong></p><pre>// Create a dummy object<br>$dummyObject = new DummyClass();<br><br>// Call a method with the dummy object as a parameter<br>$result = $testedObject-&gt;someMethod($dummyObject);</pre><h3>Spy</h3><p>A spy is a type of test double that records how it was interacted with during the test. It allows you to verify that certain interactions took place after the fact.</p><p><strong>Example in PHP:</strong></p><pre>// Create a spy for the Logger class<br>$loggerSpy = $this-&gt;getMockBuilder(Logger::class)-&gt;getMock();<br><br>// Expect the &#39;log&#39; method to be called once<br>$loggerSpy-&gt;expects($this-&gt;once())<br>          -&gt;method(&#39;log&#39;);</pre><h3>Stub</h3><p>A stub is an object that provides predefined responses to method calls made during the test. Stubs are used to isolate the code under test from its dependencies.</p><p><strong>Example in PHP:</strong></p><pre>// Create a stub for the Api class<br>$apiStub = $this-&gt;getMockBuilder(Api::class)-&gt;getMock();<br><br>// Stub the &#39;fetchData&#39; method to return a specific value<br>$apiStub-&gt;method(&#39;fetchData&#39;)-&gt;willReturn([&#39;data&#39; =&gt; &#39;fake_data&#39;]);</pre><h3>Fake</h3><p>A fake is an object that has working implementations but is simpler than the real object. Fakes are typically used for tests that require a real implementation but one that is lighter-weight or faster.</p><p><strong>Example in PHP:</strong></p><pre>// Create a fake object for the EmailSender class<br>$emailSenderFake = new FakeEmailSender();<br><br>// Set a specific behavior for the &#39;send&#39; method<br>$emailSenderFake-&gt;setSuccessfulSend(true);</pre><h3>Conclusion</h3><p>Understanding the differences between mocks, dummies, spies, stubs, and fakes is essential for writing effective and maintainable unit tests. Each type of test double serves a specific purpose and helps isolate the unit of code under test, ensuring that your tests remain focused and reliable. By leveraging these tools appropriately, you can create a robust test suite that enhances the quality of your PHP applications.</p><p>Feel free to use this article as a guide to improve your unit testing practices in PHP.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8c03b323d0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>