<?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 Parts Of Programming on Medium]]></title>
        <description><![CDATA[Stories by Parts Of Programming on Medium]]></description>
        <link>https://medium.com/@parts.of.programming?source=rss-2339a4910d8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TfqWqcGhIbIamAv47iqZxA.png</url>
            <title>Stories by Parts Of Programming on Medium</title>
            <link>https://medium.com/@parts.of.programming?source=rss-2339a4910d8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 04:08:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@parts.of.programming/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[Tagging System Design]]></title>
            <link>https://medium.com/@parts.of.programming/tagging-system-design-fa8f63d492d4?source=rss-2339a4910d8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa8f63d492d4</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[tagging]]></category>
            <dc:creator><![CDATA[Parts Of Programming]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 03:38:04 GMT</pubDate>
            <atom:updated>2025-04-03T03:38:04.768Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build a system that allows users to tag content from different products, and then to view content by tags. A goal of this system is that it should be built in a product-agnostic way, so that we could add new products in the future without a large amount of work.</h4><blockquote>💎 Take a moment to go over the initial problem statement. Ask the interviewer about possible use-case of the system which will help you build intuition as you go along.</blockquote><h3>Functional Requirements</h3><p>User should be able to:</p><ol><li>add, remove, and update tags on content (order in which tags are associated with a document is not critical)</li><li>click on a tag and see all content that has been associated with that tag</li><li>see a dashboard of popular tags (popularity: for simplicity we can assume it be defined as proportional to cardinality of content associated. we can use name as a tie breaker. a more sophisticated definition of popularity could factor in recency bias, CTR and various other signals.)</li><li>see all tags associated with a given content (required by virtue of supporting add/remove/update operation)</li></ol><blockquote>💎 The system seems to have multiple read-paths. It will be great to discuss with the interviewer regarding which is the most critical read-path and devise your data model keeping that in mind.</blockquote><h3>Anti-goals</h3><ol><li>Document Management, Security, Access Control are kept out of scope.</li><li>Bulk associating a tag with multiple documents at once is not supported.</li><li>Audit History for tracking tags added and removed.</li></ol><h3>Non-Functional Requirements</h3><p>In terms of CAP theorem, a Tagging System will usually lie in the AP domain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abo26XrhhNPssfohw9GW2w.png" /></figure><blockquote>💎 Choosing AP over CP will introduce the consistency issue. Spend some time talking about it upfront and the need to implement read-your-writes pattern to uphold user-experience.</blockquote><h3>Capacity Estimations</h3><p>Number of documents: 100 Mn<br>Number of tags: 10K<br>Average number of tags associated per document: 20<br>Average length of a tag name: 10<br>Maximum number of tags associated per document: 500<br>Maximum length of a tag name: 100</p><blockquote>💎 Introducing the max limit around tag length and associations are a sensible limit which prevents mis-use and guards against over-engineering.</blockquote><p>Size Tag Association: 100 Mn * 20 * 20 bytes = 40 * 1000 * 10⁶ = 100 * 10⁹ = 40 GB</p><blockquote>💎 Note that we don’t need to store tag name every time. Instead we can associate tag name with tag id which can be of 4 bytes only and keeping buffer for metadata still puts it around 20 bytes only.</blockquote><p>(Replication overheads are over and above this)</p><h3>High-Level Design</h3><h3>Core Entities</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*UlE3hmnRowFF0sm1BuMQYw.png" /></figure><h3>API Interfaces</h3><p><strong><em>Headers</em></strong></p><blockquote>💎 Security while critical is not the core of this (and various such) problems. So prefer to use stateless mechanisms and move fast.</blockquote><p>We will use JWT for both authentication and authorization. JWT is structured as header.payload.signature where payload can contain who the user claims to be and the scope that has been assigned. Keep in mind that payload is encoded and not encrypted so avoid putting sensitive information here.</p><p>In addition, we will support headers for tenant-id and request-id for better traceability.</p><pre>Authorization: Bearer &lt;JWT&gt;<br>X-Tenant-Id: &lt;&gt;<br>X-Request-Id: &lt;&gt;</pre><blockquote>💎 Remember to follow core API design principles. This helps keep the design consistent and intuitive for everyone.</blockquote><ul><li><strong>CRUD Tags</strong></li></ul><pre>POST /v1/content/{content_src}/{content_id}/tags<br>{<br>  &quot;tags&quot;: [<br>   {<br>    &quot;id&quot;: &quot;...&quot;<br>   },<br>   {<br>    &quot;name&quot;: &quot;...&quot;<br>   },<br>   ...<br>  ]<br>}<br><br>Status: 201 # Created<br>Status: 400 # Validation issue (max tags or max tag length)<br>Status: 401 # Authentication issue<br>Status: 403 # Authorization issue<br>Status: 422 # Unprocessable Entity<br><br>---------<br><br>GET /v1/content/{content_src}/{content_id}/tags?pageSize=10&amp;page=0&amp;sortBy=&lt;&gt;<br><br>Status: 200 # OK<br>{<br> &quot;tags&quot;: [<br>  {<br>   &quot;id&quot;: &quot;...&quot;,<br>   &quot;name&quot;: &quot;...&quot;,<br>   &quot;count&quot;: ...<br>  },<br>  ...<br> ],<br> &quot;totalCount&quot;: ...,<br> &quot;hasNextPage&quot;: ...<br>}<br>Status: 400, 401, 403<br><br>---------<br><br>DELETE /v1/content/{content_src}/{content_id}/tags<br>{<br> &quot;tagIds&quot;: [&quot;...&quot;, &quot;...&quot;, ...]<br>}<br><br>Status: 202 # Accepted<br>Status: 401, 403<br><br>---------<br><br>GET /v1/tags/{tag_id}/contents?pageSize=10&amp;page=0&amp;sortBy=&lt;&gt;<br><br>Status: 200 # OK<br>{<br> &quot;docs&quot;: [<br>  {<br>   &quot;contentSrc&quot;: &quot;...&quot;<br>   &quot;contentId&quot;: &quot;...&quot;<br>  }<br> ],<br> &quot;totalCount&quot;: ...,<br> &quot;hasNextPage&quot;: ...<br>}<br>Status: 400, 401, 403</pre><blockquote>💎 Since HATEOAS links inclusion is very opinionated in nature — discuss with the interviewer that they improve discoverability, reduces coupling and support contextual navigation, but they also add b/w overhead. If the mutual decision is to include them, add a “_link” block as shown below, otherwise skip it and move on.<br>&quot;_links”: {<br> “content”: “/v1/tags/t1/contents”,<br> …<br>}</blockquote><ul><li><strong>Popular Dashboard</strong></li></ul><pre>GET /v1/tags?pageSize=10&amp;page=0&amp;sortBy=popular<br><br>Status: 200 # OK<br>{<br> &quot;tags&quot;: [<br>  {<br>   &quot;id&quot;: &quot;...&quot;,<br>   &quot;name&quot;: &quot;...&quot;,<br>   &quot;count&quot;: ...<br>  },<br>  ...<br> ],<br> &quot;totalCount&quot;: ...,<br> &quot;hasNextPage&quot;: ...<br>}<br><br>Status: 400, 401, 403</pre><h3>Query Patterns</h3><pre>-- CREATE FLOW<br>INSERT IGNORE INTO tag(name, created_by)<br>VALUES <br> (&quot;ABC&quot;, &quot;...&quot;),<br> (&quot;DEF&quot;, &quot;...&quot;);<br><br>SELECT id<br>FROM tag<br>WHERE name IN (&quot;ABC&quot;, &quot;DEF&quot;);<br><br>INSERT IGNORE INTO tag_association(tag_id, content_src, content_id, created_by)<br>VALUES<br> (24, &quot;docs&quot;, &quot;j2u823&quot;, &quot;...&quot;),<br> (89, &quot;docs&quot;, &quot;j2u823&quot;, &quot;...&quot;);<br><br>-- DELETE FLOW<br>DELETE FROM tag_association<br>WHERE content_src = &quot;docs&quot; AND content_id = &quot;j2u823&quot; AND tag_id in (24, 89);<br><br>-- READ FLOW<br>SELECT ta.tag_id, t.name, t.count<br>FROM tag_association ta<br>LEFT JOIN tag t ON ta.tag_id = t.id<br>WHERE ta.content_src = &quot;docs&quot; AND ta.content_id = &quot;j2u823&quot;<br>ORDER BY ta.created_ts DESC<br>LIMIT 10<br>OFFSET 0;<br><br>SELECT content_src, content_id<br>FROM tag_association<br>WHERE tag_id = 24<br>ORDER BY created_ts DESC<br>LIMIT 10<br>OFFSET 0;<br><br>SELECT id, name, count<br>FROM tag<br>ORDER BY count DESC, name ASC<br>LIMIT 10<br>OFFSET 0;</pre><h3>System Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sbu9ovbBmgzy7o0IYw9W6A.png" /></figure><p><strong>API Gateway:</strong> responsible for Load Balancing, SSL Termination, Authn/Authz, Rate Limiting.</p><p><strong>BFF:</strong> responsible for orchestrating the flow across tag service and content service and stitching the final response.</p><p><strong>Tag Service:</strong> responsible for managing and exposing content-tag association.</p><p><strong>Content Services:</strong> responsible for managing the content and providing an API to bulk fetch content mini info given a list of content id in the current context.</p><h3>Refinements</h3><p><strong><em>High-Availability</em></strong></p><p>We can setup the cluster with a primary server and multiple secondary servers. This will ensure that if the primary goes down, one of the secondary servers can be promoted as primary and ensure that the application continues to function.</p><p><strong><em>Improving Performance</em></strong></p><p>To cater to performance needs, we can:</p><p>A. introduce relevant indexes in our database based on the query patterns described above</p><pre>/*<br>INDEX on tag_association:<br>	content_src, content_id, tag_id<br>	tag_id<br><br>INDEX on tag:<br> id<br> name<br> count<br>to improve performance further, we can experiment creating covering index<br>*/</pre><p>B. introduce a redis cache which can be used to cache recent traffic with appropriate cache invalidation strategy (esp. for GET /v1/content/{content_src}/{content_id}/tags API)</p><p><strong><em>Observability &amp; Analytics</em></strong></p><p>Integrating backend systems (services and databases) with OpenTelemetry and sending the metrics to a metrics backend such as Prometheus.</p><p>In addition, we will collect click-stream interaction data from the client side as part of our analytics pipeline to better compute popularity as a score rather than solely relying upon tag.count as a proxy for it.</p><p>For incorporating audit support into our system, we can simply add an audit table in our schema and execute DML operations in a transaction spanning the original table and audit table.</p><p><strong><em>Scalability</em></strong></p><p>While at current scale a single Mysql shard will be enough to sustain the traffic. However, if the system needs to provide horizontal scalability, we will need to support sharding. MySQL doesn’t have a native support for sharding (implemented by 3P wrappers). As a result we can move to MongoDB or cassandra for our data model. However, this will impact some of our query patterns and data model as described below.</p><p><strong>MongoDB</strong></p><pre># tag collection<br>{<br> &quot;id&quot;: &quot;...&quot;,<br> &quot;name&quot;: &quot;...&quot;,<br> &quot;count&quot;: ...<br>}<br><br># content_tag collection<br>{<br> &quot;content_src&quot;: &quot;&quot;,<br> &quot;content_id&quot;: &quot;&quot;,<br> &quot;tags&quot;: [<br>  24,<br>  89<br> ]<br>}<br><br>content_src, content_id forms a composite key.<br>secondary indexes on tags to support search by tag_id over content_tag.<br>join b/w content_tag and tag collection to be handled on the applicaiton side.<br><br>sharding is done based on (content_src, content_id).<br>as a result query by tag_id will lead to scatter-gather pattern.</pre><p><strong>Cassandra</strong></p><pre>CREATE TABLE tag (<br>  name TEXT,<br>  created_by UUID,<br>  created_ts TIMESTAMP,<br>  count INT,<br>  PRIMARY KEY (name)<br>);<br><br>CREATE MATERIALIZED VIEW tag_by_count AS <br>SELECT name, count, created_by, created_ts <br>FROM tag <br>WHERE count IS NOT NULL<br>PRIMARY KEY (count, name)<br>WITH CLUSTERING ORDER BY (name ASC);<br><br>CREATE TABLE content_tags (<br>  content_src TEXT,<br>  content_id TEXT,<br>  tag_name TEXT,<br>  created_by UUID,<br>  created_ts TIMESTAMP,<br>  PRIMARY KEY ((content_src, content_id), tag_name)<br>);<br><br>CREATE TABLE tag_lookup (<br>  tag_name TEXT,<br>  content_src TEXT,<br>  content_id TEXT,<br>  PRIMARY KEY (tag_name, content_src, content_id)<br>);</pre><p>We will chose MongoDB for easier implementation. For improving read scalability, we can introduce read-replicas</p><p><strong><em>Searching</em></strong></p><p>The current set of requirements doesn’t warrant creating a dedicated search backend. However, as the need grows and fuzzy search, complex filtering and faceting behavior are required to be supported — we may want to incorporate Lucene-based databases and leverage the search capabilities at the cost of consistency (albeit eventual).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNIJlo-EuRxwWhM30q-xZQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa8f63d492d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Analytics Platform System Design]]></title>
            <link>https://medium.com/@parts.of.programming/analytics-platform-system-design-c428b9677604?source=rss-2339a4910d8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c428b9677604</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[analytics-platforms]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <dc:creator><![CDATA[Parts Of Programming]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 10:49:29 GMT</pubDate>
            <atom:updated>2025-02-26T10:49:29.362Z</atom:updated>
            <content:encoded><![CDATA[<h4>Design an Analytics platform that stores various data/metrics and allows users to run analytics for a large-scale application.</h4><blockquote>💎 Designing an Analytics platform is a very wide problem statement. There are large amount of tools and technologies out there. Start with laying down the generic architecture first and introduce technology stack with explanations along with way.<br>While you should strive for creating a solution which should be adaptable to changing organization needs, in context of the interview, work with your interviewer to list down some sample business use-cases that they would want the platform to deliver. This will help verify the E2E working of the solution.</blockquote><h3>Functional Requirements</h3><ol><li>Should be able to connect to various type of data sources for ingestion</li><li>Should be able to provide mechanisms related to governance, validation and quality management</li><li>Should be able to connect to various type of data sinks which can be used for visualization</li><li>[P1] Should be able to prepare business reports in a recurring fashion and deliver them to internal users.</li><li>[P1] Should be able to cater to security requirements for critical data.</li></ol><p>Sample Specific use-case:</p><ol><li>Path Analysis for user journey on the app</li></ol><h4>Anti-goals</h4><ol><li>Creating a system that requires manual scaling during traffic spikes</li><li>Creating a no-code platform for analytics</li></ol><h3>Non-Functional Requirements</h3><p>In terms of CAP theorem, majority of the components of analytics system will usually lie in the AP Domain with a few components being made CP or tunable as per use-case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJAjKwSVBosAL5BtlDKGaA.png" /></figure><h3>High-Level Design</h3><blockquote>💎 Analytics Platform System Design usually won’t follow the standard format of Backend Engineering Design where we have enough clarity on creating Core Entities upfront.</blockquote><h4>Technical Decisions</h4><p><strong><em>Getting the Data</em></strong></p><p>An analytics platform should be able to cater to wide variety of sources to avoid friction while onboarding. Some of the prominent use-cases that most organizations will have are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qi8WrjF0KCyiRgpMZBAE_w.png" /></figure><blockquote>🐬 Potential Deep-Dive: How to implement web-scraping</blockquote><p>A matured state of an organization’s data platform will involve presence of all the above. To bootstrap we can start with incorporating CDC Events as they can be tweaked at a central place with limited engineering benefit and help generate valuable insights by providing the capability to stitch data across components / micro-services. For generating CDC Events a popular choice is to use Debezium which provides source connectors for various databases and allow various sink connectors to configured.<br>For our use-case of User journey path analysis, we will also need to onboard Clickstream Events which are fired by app.</p><p><strong><em>Transporting the Data</em></strong></p><p>This layer helps us in collecting data from various sub-systems into a standardized event bus (message queue). Kafka and Pulsar are popular choices in this regard with inclination towards Kafka owing to wider adoption and familiarity.<br>In addition we can leverage Schema Registry to ensure validation of data format.</p><blockquote>🐬 Potential Deep-Dive: How does Kafka work internally, how are Pulsar and Kafka different.</blockquote><p><strong><em>Processing the Data</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtyD-jQPBnNhtbvToiDojQ.png" /></figure><p>Given the above characteristics, we will start with Lambda Architecture. This helps keep the operational overhead low and also solves for our immediate sample use case of User journey path analysis. As the business needs become more complex and we require near real-time analytics use-case, we can migrate relevant workloads to Kappa Architecture.<br>For implementing lambda architecture we can use Spark for batch processing layer along with Flink/Spark Streaming for stream processing layer.</p><blockquote>🐬 Potential Deep-Dive: How does Spark/Flink work internally, what are various ways to speed up a given Flink Topology or Spark Job</blockquote><p>Since batch processing needs to be executed on a scheduled basis, we can leverage Apache Airflow to manage the jobs.</p><p><strong><em>Storing the Data</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W09zgIZzOB4RhsC_376hqA.png" /></figure><p>For our use-case we will go ahead with Data Lake strategy to begin with. This allows us ease of onboarding, flexibility and ability to move fast and deliver immediate business needs.<br>As the system matures we can leverage bottom-up approach for transition where we bring up dedicated Data Marts for critical department specific use-cases followed by introducing a Central Data Warehouse (either cluster-based or serverless).</p><p><strong>Medallion Architecture</strong></p><p>A widely accepted pattern in Data Lake involves dividing the data storage into three layers: Bronze (Raw), Silver (Validated), Gold (Business).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8rejpwEpar9RiLlAnrhaaw.png" /></figure><p><strong>Logical Format</strong></p><p>For the gold layer of data lake, we can organize our data into the following schema for ease of retrieval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4a3k1fTecvnIrILBNxOWFw.png" /></figure><p>We can begin with Star schema for immediate business needs and evolve into Galaxy schema as more business use-cases are onboarded. As and when the business complexity and the need for representing hierarchical relationships increases we can adapt the specific use-cases to Snowflake schema. (Note that normalizing the dimensions table will incur cost during querying time due to the need for performing excessive joins)</p><blockquote>💎 Spend a few minutes here to draw skeleton of “Core Entities” for a sample business case mentioned in our requirements. We need not be exhaustive here in terms of field that we are introducing. Key idea will be represent the use of Star schema along with use of surrogate keys for flexibility and resilience to implementation changes.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D2OeKoDQV_hf4msUhq-oeA.png" /></figure><p><strong>Physical Format</strong></p><p>This represents how the data will be stored on disk</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlclhFtvU5kiQsZUSQxgjw.png" /></figure><p>We will take a multi-pronged approach here. For Bronze layer we will go ahead with storing data in parquet format for achieving better storage efficiency. In addition we can preserve the native format as well in case of compliance needs. For non-text formats we can store them in native format by creating a companion file using parquet. For silver and bronze wherever transactional support is required and/or updates/merges are common, we can go ahead with Delta, otherwise Parquet.<br>In addition the metadata — schema, partitions can be stored in Hive Metastore for easier querying.</p><blockquote>🐬 Potential Deep-Dive: Delta Format and Parquet Specifications. Internals of Hive Metastore</blockquote><p><strong><em>Serving the Data</em></strong></p><p>Depending upon the use-case we can expose multiple tools in this layer. For batch processing / adhoc use-cases, we can go ahead with Trino and Spark SQL.<br>For Real-Time processing use-cases, we would want to store them in Pinot or Druid which are optimized for these workloads.<br>In addition, we can introduce Aerospike for storing pre-aggregated features as key-value pairs which can be directly leveraged by backend applications for very low latency use-cases.</p><p><strong><em>Presenting the Data</em></strong></p><p>Similar to Serving Layer, idea will be to expose multiple tools to cater to various user needs. Grafana and Metabase for dashboarding, API integration for custom reporting needs and Jupyter access for allowing engineering and analytics team to perform Exploratory Data Analysis.</p><h3>System Diagram</h3><p>Stitching the above pieces together</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmmJOp0RSwjrswK8woHEfg.png" /></figure><h3>Refinements</h3><ol><li>Caching layer on top of Trino to optimize querying performance.</li><li>Data Quality Monitoring Agents to validate various layers of data storage.</li><li>Integration with OpenTelemetry across the tech stack to provide better monitoring of the data pipeline.</li><li>Enabling ACL for various touch-points to prevent unauthorized access.</li><li>Incorporating Masking Stage during ingestion and transformation to mask sensitive user-data</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c428b9677604" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[URL Shortener System Design]]></title>
            <link>https://medium.com/@parts.of.programming/url-shortener-system-design-19c77fa2ebc2?source=rss-2339a4910d8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/19c77fa2ebc2</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[tinyurl-system-design]]></category>
            <category><![CDATA[url-shorteners]]></category>
            <dc:creator><![CDATA[Parts Of Programming]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 07:54:50 GMT</pubDate>
            <atom:updated>2025-02-25T07:54:50.861Z</atom:updated>
            <content:encoded><![CDATA[<h4>Design a system to generate unique short URLs for a given URL</h4><blockquote>💎 URL Shortener is a beginner-friendly problem but can be asked even to senior candidates. In such a case, the focus should be on delivering and discussing the base solution as fast as possible, calling out failure handling and recovery scenarios and covering around two P1 requirements as part of refinements.</blockquote><h3>Functional Requirements</h3><p>User should be able to:</p><ol><li>generate a unique short URL for a given URL</li><li>delete the short URL created by the same user</li><li>update the target URL for a given short URL created by the same user</li><li>optionally configure expiry against the short URL</li><li>[P1] optionally provide a custom short URL</li><li>[P1] view analytics around number of visits, geographical distribution, etc.</li></ol><p>System should be able to:</p><ol><li>return the existing short URL for a given URL and user, if it already exists.</li><li>[P1] prevent abuse from malicious users</li><li>[P1] allow expired URLs to be re-purposed</li><li>[P1] reduce the likelihood of loosing short URL keys</li></ol><h4>Anti-goals</h4><ol><li>It is acceptable to have predictability in random URL generation.</li><li>User authentication, ACL and management are handled by other existing systems.</li></ol><h3>Non-Functional Requirements</h3><p>A URL Shortener system will usually be divided into two sub-components: indexing and querying following the CQRS pattern. In terms of CAP theorem, indexing system will lie in CP domain to ensure no two URLs are assigned to the same short URL. The querying system will however prioritize availability to meet the scale demands by settling for eventual consistency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUQ8Z4eQgbKD6WEKrOb5DQ.png" /></figure><h4>Capacity Estimations</h4><blockquote>💎 In comparison to other problems, correctly estimating capacity is one of the key evaluation parameters in the interviewer checklist here. Don’t forget to explicitly call-out the need for using Base62, length of short URL that will be required to support the system scale (e.g. 7 characters are required in this case) and negotiating on the read-write ratio with the interviewer.</blockquote><p>Number of new URLs generated / day: 10 Mn<br>Number of new URLs generated / sec: 10 Mn / 86400 = 120</p><blockquote>ℹ️ Assumption: peak generation rate to be 10 times of the average.</blockquote><p>Peak write TP: 1.2K writes/sec</p><blockquote>ℹ️ Assumption: system is heavily skewed towards reads with read-write ratio 100:1</blockquote><p>Peak read TP: 12K read/sec<br>Total URLs to be stored in 10 years: 10 Mn * 365 * 10 = 40 Bn<br>Avg length of long URL: 100 bytes<br>Encoding format to be used for short URL: Base62</p><blockquote>ℹ️ Base62 will be used irrespective of the strategy that we use for generation. This is because Base62 is composed of URL safe characters A-Za-z0–9.</blockquote><blockquote>Another popular encoding is Base58 which omits the characters which might be confused with each other 0, O, I, l. Using this encoding makes sense if a user is expected to share this code verbally as part of the workflow.</blockquote><p>Maximum length of short URL: ceil(log(2 * 10¹², 62)) = 7<br>Average Record size (including metadata): 150 bytes<br>Storage requirement / year: 10 Mn * 365 * 150 = 550 GB<br>Storage requirement for 10 years: 6 TB</p><blockquote>ℹ️ Assumption: distribution follows pareto principle, hence 80% of the traffic comes from 20% of the URLs</blockquote><p>Additional Caching storage to be added per year: 550 GB * 0.2 = 110 GB<br>Peak read on DB: 12K * 0.2 = 2.4K read/sec</p><h3>High-Level Design</h3><blockquote>💎 We can start defining entities in an ER model, and assume to store things in an RDBMS. But remember to verbally callout the need to review this decision later, especially around the NFRs.</blockquote><blockquote>This methodology helps us deliver a workable MVP solution faster and leaves room for refinements subsequently after.</blockquote><h4>Core Entities</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*0DngjiXSv5JxtbX5J7zzGg.png" /></figure><p><strong>User</strong>: responsible for storing user profile attributes</p><p><strong>Mapping</strong>: responsible for storing the assignment b/w short URL and the target URL. It additionally maintains the metadata around the user who configured the Mapping to prevent updates from other users.</p><blockquote>⏳ It is important to realize that this problem doesn’t have much depth in Core Entities and hence spend only a fraction of time in setting up the context</blockquote><h4>API Interfaces</h4><p><strong><em>Headers</em></strong></p><p>In order to ensure that only valid users are able to configure URL mappings, we will authenticate the write flow using stateless mechanisms such as JWT to keep things simple for now.</p><pre>Authorization: Bearer ...</pre><p>For the read traffic, we may want to expose it to all visitors irrespective of if they have signed up on the platform or not which eradicates the need for authentication layer for those APIs.</p><p><strong>Generate a short URL</strong></p><pre>POST /v1/shorten<br>{<br> &quot;targetUrl&quot;: &quot;...&quot;,<br> &quot;resource&quot;: &quot;...&quot;, // optional<br> &quot;expiryDate&quot;: &quot;...&quot; // optional<br>}<br><br>Response<br>Status: 200 # Ok<br>{<br> &quot;resource&quot;: &quot;...&quot;<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 429 # Too Many Requests<br>Status: 422 # Conflict if custom resource provided is already being used or reserved</pre><blockquote>💎 Industry practice for communicating validation and/or conflict error is either 409 or 422. We can choose either of them, provided we callout both the options.</blockquote><p><strong>Update a short URL mapping</strong></p><pre>PUT /v1/shorten<br>{<br> &quot;resource&quot;: &quot;...&quot;<br> &quot;targetUrl&quot;: &quot;...&quot;,<br> &quot;expiryDate&quot;: &quot;...&quot; // optional<br>}<br><br>Response<br>Status: 200 # OK (if targetUrl mapping already exists for the current user)<br>{<br> &quot;resource&quot;: &quot;...&quot;<br>}<br><br>Status: 201 # Created<br>{<br> &quot;resource&quot;: &quot;...&quot;<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization (not owned by the user)<br>Status: 429 # Too Many Requests<br>Status: 422 # Conflict if targetUrl is already mapped to another resource by the same user</pre><p><strong>Delete a short URL mapping</strong></p><pre>DELETE /v1/shorten?resource=&quot;...&quot;<br><br>Response<br>Status: 200 # Ok (even if the resource doesn&#39;t exists)<br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization (not owned by the user)</pre><p><strong>Get target URL</strong></p><pre>GET /v1/&lt;resource&gt;<br><br>Response<br>Status: 302 # Temporary Redirect<br>Response Header: Location: &lt;target_url&gt;<br><br>Status: 404 # Not Found (or if expired)</pre><blockquote>💎 Key highlight of this section is discussion around choosing the right status codes. Talk about nuances of:<br><strong>301 (Moved Permanently)</strong><br><strong>302 (Temporary Redirect)</strong><br>303 (See Other)<br>307 (Temporary Redirect with same HTTP method)<br>308 (Permanent Redirect with same HTTP method)<br>400 (Bad Request)<br>404 (Not Found)<br>409 (Conflict)<br>410 (Gone)<br>414 (URI too long)<br><strong>422 (Unprocessable Entity)</strong></blockquote><h3>System Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GFokEMbLTayjnqfpWFL00Q.png" /></figure><p><strong>API Gateway:</strong> responsible for providing load-balancing, authentication, redirecting and rate limiting capabilities.</p><p><strong>URL Manager:</strong> responsible for assigning short URL to a long URL. The workflow involves validation of the resource if a custom one has been provided against reserved keywords, duplication, etc. This is also responsible for generating the short URL resource name which can be assigned to the incoming write requests.</p><p><strong>Redirection Service:</strong> responsible for returning the long URL for the given short URL</p><p><strong><em>Technical Decisions</em></strong></p><p><strong>Short URL resource generation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOva-DBQSIHj3kv86BevzQ.png" /></figure><p>Basis the above discussion we will go ahead with Counter based approach as it is simpler to implement and will circumvent its short-comings by:</p><ol><li>incrementing the counter by say 100 instead of 1 and fetching for the next counter range only once the previously fetched range is consumed or closer to getting consumed.</li><li>server can also choose to randomly pick amongst N : N+100 counters which it had fetched. The predictability can be obscured even further by splitting the counter universe into K contiguous parts and randomly choosing to increment one of the sub-counter at a time.</li><li>server which recently fetched range N : N+100 may subsequently crash leading to lost ranges. This can be dealt with via a scavenging job which pushes these ranges to a distributed Message Queue.</li><li>the scavenging job introduced in the previous step can be extended to also handle expired resources thus improving the efficiency of the system.</li></ol><p><strong>Counter DB</strong></p><p>Required Characteristics: Atomicity, Durability</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MDMTo3yyL-nbVz2Gzjle7Q.png" /></figure><p>Peak write TP: 1.2K / sec with batch size of 100 during increment, this becomes 12 updates/sec which is well within the limits of an RDBMS and hence we will stick to MySQL as our choice here.</p><p><strong>URL DB</strong></p><p>Required Characteristics:</p><ol><li>Avoid multiple entries with same short URL resource (primary key constraint)</li><li>Avoid multiple entries with same user and target URL (uniqueness constraint)</li><li>[Good-to-have] Support record expiry</li><li>Support 3K-6K / sec read throughput on an average.</li><li>Horizontal Scalability</li><li>Durability</li></ol><p>Given the above constraints: DynamoDB, MongoDB and Aerospike are probable options that we could consider. We will go ahead with Aerospike for the following reasons:</p><ol><li>1.2K IOPS are within the SSD performance limits to support durability</li><li>provides tiered storage (memory + SSD) and thus can simplify querying by providing read-through caching pattern.</li><li>can support consistency using application-side logic by running transactions across two sets</li></ol><p><strong>Cache</strong></p><p>As highlighted above, we can stick to Aerospike for our caching needs as well thus reducing maintenance overhead.</p><blockquote>💎 In case interviewer limits our options by asking us to choose OSS stack, we can go ahead with MongoDB + Redis combination.</blockquote><p><strong>Message Queue</strong></p><p>Required Characteristics: HA, HS, ability to allow multiple consumers to listen to the events at their own processing speed.</p><p>Kafka and Pulsar are both valid choices with inclination towards Kafka owing to wider adoption and operational familiarity.</p><h3>Refinements</h3><p><strong><em>Scavenging Workflow</em></strong></p><p>This additional component caters to the following P1 requirements:</p><ol><li>allow expired URLs to be re-purposed</li><li>reduce the likelihood of loosing short URL keys</li></ol><p>Setup an Airflow job which iterates over the URL DB in batches and recovers any missing counters and pushes the same to Message Queue. URL Manager consumes from Message Queue in addition to fetching fresh counters from Counter DB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xpc4ikG7742chGUH94z31Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19c77fa2ebc2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leaderboard System Design]]></title>
            <link>https://medium.com/@parts.of.programming/leaderboard-system-design-d4f17630a63b?source=rss-2339a4910d8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4f17630a63b</guid>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Parts Of Programming]]></dc:creator>
            <pubDate>Mon, 24 Feb 2025 15:45:10 GMT</pubDate>
            <atom:updated>2025-02-24T15:45:10.344Z</atom:updated>
            <content:encoded><![CDATA[<h4>Design a system for showing leaderboard for a popular sports game.</h4><blockquote>💎 One of the most critical aspects of a leaderboard system is the type of window ranges to be supported — Fixed Window, Rolling Window or custom time frame at runtime. This will have a substantial impact on the design choices.</blockquote><blockquote>In addition, get clarification on the range of variable K and tie-breaking strategies.</blockquote><h3>Functional Requirements</h3><ol><li>Record points scored by users. A player wins a point if they win a match.</li><li>Show top-K ranked users across various time-segments: this week, this month, this year, all-time and K ≤ 100.</li><li>Leaderboard should be updated in near real time</li><li>Show the percentile of the current user.</li><li>Tie-break in case two users have the same score</li></ol><blockquote>💎 Identifying the edge cases and clarifying the expectations around them in advance will demonstrate your critical thinking ability.</blockquote><h4>Anti-goals</h4><ol><li>Querying support for custom time ranges on the leaderboard metrics is not needed.</li><li>An existing system already takes care of game management and execution.</li><li>User/Player onboarding and management are out-of-scope and exist as separate components.</li></ol><h3>Non-Functional Requirements</h3><blockquote>💎 Always proactively communicate whether you would choose to build the system as and AP or CP system along with why. Also note, many a times the solution may involve designing multiple components and it is totally fine if system X is AP but system Y is CP.</blockquote><p>In terms of CAP theorem, a Leaderboard will usually lie in the AP Domain with the understanding that users will be able to tolerate minor delays or small period of inconsistencies in the leaderboard data.</p><p>High Availability Acceptable to show a leaderboard during network partitions even if the view might not be consistent at that time Horizontally Scalable The number of users could increase substantially over period Performance Leaderboard should be updated in near-real time as the player’s score/points change. Current state of the leaderboard should be fetched within milliseconds. Observability Ability to monitor lag in the system. RED metrics Security Prevent player scores from being tampered. Fault Tolerance Ability to reconcile and show eventually consistent states</p><h4>Capacity Estimations</h4><p>Number of players: 100 Mn<br>Avg number of matches / player / day: 10<br>Storage space / player / window: 200 Bytes<br>Total Storage space / window: 200 * 100 * 10⁶ = 20 GB<br>Estimated Storage space / window: 20 GB * 4 = 80 GB<br>Number of updates / day: 10 * 100 Mn = 1 Bn<br>Number of updates / sec: 10⁹ / 10⁵ = 10K ops/sec<br>Peak updates: 10K * 10 = 100K ops/sec<br>Number of viewers: 1 Bn<br>Number of concurrent visitors: 300 Mn</p><h3>High-Level Design</h3><h4>Core Entities</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*NSxeSy7ZCBuJ9PQzvOYEzA.png" /></figure><p><strong>Player</strong>: responsible for storing the profile attributes of the given player.</p><p><strong>Timeframe-X-Leaderboard:</strong> represents a given fixed-window time frame against which the score is being tracked. For weekly leaderboards, we will have separate leaderboards created every week. Likewise for months and years. In addition, we will have an all-time leaderboard.</p><blockquote>⏳ It is important to realize that this problem doesn’t have much depth in Core Entities and hence it is important to spend only a fraction of time in setting up the context</blockquote><h4>API Interfaces</h4><p><strong><em>Headers</em></strong></p><p>In order to ensure that the player scores aren’t being tampered, we will authenticate the update flow using stateless mechanisms such as JWT to keep things simple for now.</p><pre>Authorization: Bearer ...</pre><p>For the read traffic, we may want to expose it to all visitors irrespective of if they have signed up on the platform or not which eradicates the need for authentication layer for those APIs.</p><p><strong>Update score</strong></p><pre>POST /v1/scores<br>{<br> &quot;data&quot;: {<br>  &quot;playerId&quot;: &quot;...&quot;,<br>  &quot;score&quot;: 1,<br>  &quot;gameId&quot;: &quot;...&quot;<br>}<br><br>Response<br>Status: 202 # Accepted<br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization</pre><p><strong>View Leaderboard</strong></p><pre>GET /v1/scores?window=...<br><br>Response<br>Status: 200 # OK<br>{<br> &quot;data&quot;: [<br>  {<br>   &quot;playerId&quot;: &quot;...&quot;,<br>   &quot;score&quot;: 4372,<br>   &quot;rank&quot;: ...<br>  },<br>  {<br>   &quot;playerId&quot;: &quot;...&quot;,<br>   &quot;score&quot;: 929,<br>   &quot;rank&quot;: ...<br>  },<br>  ...<br> ]<br>}<br>Status: 429 # Breaching capacity constraints</pre><p><strong>View User Statistics</strong></p><pre>GET /v1/scores?player=...<br><br>Response<br>Status: 200 # OK<br>{<br> &quot;data&quot;: {<br>  &quot;playerId&quot;: &quot;...&quot;,<br>  &quot;score&quot;: 4372,<br>  &quot;rank&quot;: ...,<br>  &quot;percentile&quot;: ...<br> }<br>}<br>Status: 429 # Breaching capacity constraints</pre><blockquote>⏳ Similar to the Core Entities section, APIs for this problem are pretty straight-forward and hence ensure that you breeze-past this section fairly quickly. There is a good chance that your interviewer shares the same view. However, keep in mind to not implicitly assume it. Instead, verbalize your thought-process, bring them on the same page and then proceed to the next section.</blockquote><h3>System Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jvX7bWTCVyj3cGT9bJ2DGg.png" /></figure><p>We will be dividing the responsibility of the flow using CQRS pattern. This helps us achieve better separation of concerns, avoiding SPoF and individually scale-up the respective components as per the business need.</p><p><strong>Leaderboard Service:</strong> Responsible for returning the leaderboard details — top-K players, current player score and percentile for the selected window.</p><p><strong>Score Updates:</strong> Responsible for receiving update requests from the upstream (usually game service). This layer may run some additional validation checks before forwarding it to a Message Queue.</p><p><strong>Score Consumer:</strong> Responsible for reading the events from the Message Queue and updating the counter in all the respective leaderboards for the respective player.</p><blockquote>💎 Keep the system architecture generic in nature without jumping into tech choices upfront. Identify the need for a particular component, then what access pattern a particular component needs. Propose more than one tech choice that could be considered and conclude by selecting one amongst them backed by reasoning.</blockquote><blockquote>This strategy will help demonstrate your technical breadth, depth and your ability to take decisions amongst ambiguity by breaking down the problem.</blockquote><p><strong><em>Technical Decisions</em></strong></p><p><strong>Leaderboard DB</strong></p><p>Responsible for storing the score against each player for the specific time-frame. Access patterns required to be supported:</p><ol><li>Atomically increment the score for a given player_id.</li><li>Find the top-K players by score where K can be dynamic but not higher than 100</li><li>Find the score, rank, percentile of a player by id</li><li>Process 100K peak updates / second</li><li>Process 300Mn peak reads / second</li><li>Storage requirements: 80 GB / window</li></ol><p><strong>Choices</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPtM5J7rwhJ1uymZcoxknw.png" /></figure><blockquote>💎 We could have also gone ahead with Redis Sentinel setup. However, we chose to go ahead with Redis Cluster in this case owing to the need for both HA and HS.</blockquote><p>Given the above, we will choose to go ahead with Redis Cluster setup. However, this introduces the need to partition the data amongst cluster master nodes.</p><p><strong>Partitioning</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HVxgA0WfN4B1n5BOH0sOg.png" /></figure><p>Both the partitioning strategies come with their own set of caveats. The right answer is subjective here and depends upon the UX requirements that we had documented earlier. Given the current scenario where we need to show only percentiles and not exact rank of a player, we can circumvent the bottlenecks by:</p><ol><li>Assuming percentile of a player within its bucket is same as across all buckets (since the players are randomly distributed)</li><li>Caching the leaderboard top-K snapshot in a separate key with cache-aside strategy to avoid scatter-gather on every leaderboard load request.</li></ol><p><strong>Message Queue</strong></p><p>Responsible for providing pub-sub pattern for score updates. Access patterns required to be supported:</p><ol><li>delivery guarantees</li><li>horizontal scalability by partitioning</li><li>allow multiple consumers to be attached to the same event stream</li><li>allow consumers to seek back to point-in-time for recovery use-cases</li><li>provision to archive old data automatically by providing tiered storage support and clean-up policies</li><li>ability to monitor lag in the processing pipeline</li></ol><p>Both Kafka and Pulsar can suffice our use-case above while RabbitMQ falls short in the (4), (5) points above. Owing to wider adoption, lesser moving parts and familiarity we will go ahead with Kafka as our choice.</p><p><strong>Partition Key</strong></p><p>We can choose to keep player_id as our partition key for the topic. We can also do application-level sharding by distributing the players across multiple kafka topics for easing out any migration processes down the line.</p><h3>Refinements</h3><p><strong><em>Failure Recovery</em></strong></p><p>Use of Redis Sorted Sets introduces the need to handle durability constraints as in the default set-up, redis doesn’t provide reliable persistence since the data is stored in memory only.</p><p>Redis Cluster already has leader-follower architecture which reduces the likelihood of data loss if sufficient follower replicas are configured per leader. In case leader node goes down, one of the follower replicas take over. However, there is a likelihood of data loss where the most recent updates done on leader weren’t yet propagated to the followers yet. We can fine tune it via configuring min-replicas-to-write setting to reduce the likelihood even further but this comes at a cost on write speed.</p><p>Enabling persistence — AOF or RDB can further help in reducing the time window of data loss. However, they don’t completely rule out the likelihood either. In addition, AOF may have noticeable impact on the write performance. Whereas RDB introduces the cost of maintenance overhead of multiple snapshots across the cluster.</p><p>Using Kafka Consumer seek operation to replay events which got missed while keeping the update operation idempotent by maintaining additional metadata (updated_ts and updated_offset)</p><p>Creating checkpoint snapshot in Blob store on a daily basis and reconciling the scores of players in batches. This strategy works if we are allowed to introduce maintenance window for a small duration once every day.</p><p>Lastly, an alternate strategy is to do parallel writes to a more resilient database which can provide the durability requirements and keep-up with the write speed. The data can be modelled in a format where we record the points scored along with respective metadata as this will be beneficial for auditing use-cases as well. Cassandra and ScyllaDB fits the criteria best here with inclination towards ScyllaDB for being more actively maintained.</p><p>We will go ahead with a combination strategy: redis cluster + checkpoint snapshot with maintenance window + consumer offset reset. To execute the strategy we will also need to</p><ol><li>keep the writes idempotent via lua scripts (using updated_ts and updated_offset)</li><li>temporarily pause new writes via recovery locks</li><li>display a maintenance banner to the end user to better communicate</li><li>ensure that recovery script execution is significantly faster than the write throughput during the maintenance window for the catchup to happen.</li></ol><p>The above strategy helps us keep the recovery relatively simpler and cost efficient.</p><blockquote>💎 In circumstances like these where there is no “single right answer”:<br>1. stating multiple possible approaches demonstrates your breadth of knowledge<br>2. calling out pros/cons of each approach demonstrates your technical depth<br>3. being decisive and choosing an option at the end which best fits the current requirement demonstrates your decision making skills.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4f17630a63b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ticket Booking System Design]]></title>
            <link>https://medium.com/@parts.of.programming/ticket-booking-system-design-86d7c62e03d2?source=rss-2339a4910d8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/86d7c62e03d2</guid>
            <category><![CDATA[ticketmaster]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[ticketing-system]]></category>
            <dc:creator><![CDATA[Parts Of Programming]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 12:42:39 GMT</pubDate>
            <atom:updated>2025-02-16T12:42:39.503Z</atom:updated>
            <content:encoded><![CDATA[<h4>Design a system for managing and booking tickets</h4><blockquote>💎 Ticket Booking systems usually have peculiar nuances around the type of use-case that they are trying to serve and the data model heavily depends upon the same. It will be a great to start clarifying what type of bookings can be made — movie, concert, webinar or train. This will avoid any surprises and will help limit the scope of the problem.</blockquote><blockquote>For the current case, we will assume it to be movies.</blockquote><h3>Functional Requirements</h3><p>User should be able to:</p><ol><li>see movies available for booking in the given city in alphabetical order on home page.</li><li>see movie description, trailer and cast information</li><li>place bookings for 7 days in advance only (inclusive of the current day)</li><li>while booking, allowed to select city, theatre, experience type (2D, 3D, IMAX, etc.), seat category (premium, gold, etc.) and the exact seat configuration and make payment.</li><li>visit the orders page to get the booking information</li><li>booking information should contain a QR code which can be used to get entrance permit at the theatre.</li></ol><p>Allow admin users to:</p><ol><li>manage shows on behalf of theatres</li><li>block / unblock seats owing to maintenance activity</li></ol><p>System should be able to:</p><ol><li>handle booking failures and provide refund to the users</li></ol><h3>Anti-goals</h3><blockquote>💎 Booking platform is a fairly large ecosystem and is composed of multiple sub-problems within it. Usually, the interviewers are interested in evaluating the candidate on the main booking flow unless told otherwise. Thus, it is important to communicate the need for the supporting platform components to deliver the E2E solution but negotiate upfront to keep their design out of scope in the interest of time and to stay focussed.</blockquote><ol><li>User onboarding, scheduling and notifications are handled by existing / 3P components.</li><li>Search and Recommendation are out of scope.</li><li>Payment functionality is assumed to be provided by a Payment Service Provider.</li><li>Only simple pricing constructs are expected to be supported.</li><li>Invoicing, billing, taxation and settlements are out of scope.</li></ol><h3>Non-Functional Requirements</h3><p>In terms of CAP theorem, a Ticket Booking will usually lie in the CP Domain. However, sub-parts of the system around Discovery will lie in the AP Domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gUo9-GDl_J_uEJH-7lmlSw.png" /></figure><h3>Capacity Estimations</h3><blockquote>💎 Occassionally, interviewers may choose not to share any numbers or request candidates to come up with the metrics that they think are important to the problem. In such cases follow the:</blockquote><blockquote>request path — gather metrics which can help deduce the concurrency.</blockquote><blockquote>data path — gather metrics which can help deduce the storage cost.</blockquote><p>Number of Halls onboarded (A): 10K<br>Number of Screenings / Hall / day (B): 4<br>Avg Number of seats / Hall (C ): 50<br>Avg Number of seats / booking (D): 2<br>Avg Occupancy Ratio (E): 0.7<br>Number of bookings / day: A * B * C * E / D = 700K</p><p>Assuming, live traffic period is around 8 hours per day, this translates to:<br>Average Bookings / minute: 1.5K<br>Peak Bookings / minute: 15K (assuming 10x traffic)</p><p>Assuming, overall conversion rate of around 5% and Listing to Seat Selection drop-off at 50%, this translates to: <br>read traffic / min on the List Page: 30K (Avg), 300K (Peak)<br>read traffic / min on the seat selection: 15K (Avg), 150K (Peak)</p><h3>High-Level Design</h3><h3>Core Entities</h3><blockquote>💎 A very significant part of this problem is creating the right data model. Many candidates fail to correctly identify the relationship 1:1, 0:1, 1:many, 0:many, many:many (and the need for junction table) between entities leading to inability to support one or more use-case during subsequent cross-questioning by the interviewer.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*G3nuC9QhkqxPrK6QYbzp9g.png" /></figure><p><strong>Hall:</strong> represents a screen / hall inside a theatre where screening can take place. This allows us to support both single-screen and multiplex theatres.</p><p><strong>Seat:</strong> represents a particular seat inside a Hall.</p><blockquote>❇️ Potential Level-up: What if a seat setup changes inside a Hall due to restoration activity.</blockquote><p><strong>Show:</strong> represents a particular screening at a Hall for given date-time and is also associated with the movie entity. Contains a constraint on hall_id, start_ts and end_ts to avoid instances where the same hall gets assigned to multiple screening in overlapping time frames.</p><p><strong>Pricing:</strong> represents the pricing strategy at seat category level for each show. This allows us to differentiate price across shows and across categories.</p><p><strong>Booking</strong>: represents a booking request placed by a user for given show. This allows us to aggregate the total price for all the tickets and prepare a net amount after discount deductions which needs to be collected from the user.</p><p><strong>Payment:</strong> represents the payment transaction against a booking. This tracks the status from third-party.</p><p><strong>Ticket:</strong> represent each seat booking at show level and the price at which it was booked. This allows us to enforce the integrity constraints around double booking.</p><blockquote>💎 Creating the core entities and their relationships can be a very time-consuming task. Key is to draw the high-level skeleton and drill-down only those entities which are related to critical design choices.</blockquote><h3>API Interfaces</h3><p><strong><em>Headers</em></strong></p><p>We will use headers for identifying the user. For simplicity, we can use stateless mechanism such as JWT and introduce statefull mechanisms such as OAuth later on as needed.</p><pre>Authorization: Bearer ...</pre><p><strong>Get Movies</strong></p><pre>GET /v1/movies/&lt;movie_id&gt;<br><br>Response<br><br>Status: 200 # Succesfully Fetched<br>{<br>  &quot;movieId&quot;: &quot;&quot;,<br>  &quot;movieName&quot;: &quot;&quot;,<br>  ...<br>}<br><br>Status: 404 # Not Found<br>Status: 429 # Too Many Requests</pre><blockquote>☢️ What status-code to return if there are no movies matching a particular prefix?</blockquote><blockquote>While many candidates may say 404, it is important to understand that it is incorrect because:<br>- Empty search results don’t mean the search functionality is missing<br>- Using 404 makes error handling more complex for clients &lt;/aside&gt;</blockquote><p><strong>Get Theatres</strong></p><pre>GET /v1/movies/&lt;movie_id&gt;/theatres?city=&lt;city_id&gt;&amp;pageSize=10&amp;cursorMark=&lt;&gt;&amp;date=&lt;&gt;<br><br>Response<br><br>Status: 200 # Succesfully Fetched<br>{<br>  &quot;data&quot;: [<br>   {<br>    &quot;theatreId&quot;: &quot;&quot;,<br>    ...<br>    &quot;shows&quot;: [<br>     {<br>       &quot;showId&quot;: &quot;&quot;,<br>      &quot;experienceType&quot;: &quot;&quot;,<br>      &quot;startTs&quot;: &quot;&quot;<br>      ...<br>    },<br>    ...<br>    ]<br>   },<br>   {<br>    ...<br>   },<br>   ...<br>  ],<br>  &quot;pagination&quot;: {<br>  &quot;totalCount&quot;: 29<br>  &quot;nextCursorMark&quot;: &quot;g49jw7yc&quot;<br>  }<br>}<br><br>Status: 429 # Too Many Requests</pre><p><strong>Get Show</strong></p><pre>GET /v1/shows/&lt;show_id&gt;<br><br>Response<br><br>Status: 200 # Succesfully Fetched<br>{<br> &quot;hallId&quot;: &quot;&quot;<br>  &quot;seatConfiguration&quot;: {<br>  },<br>  &quot;seatAvailability&quot;: [<br>   {<br>    &quot;id&quot;: &quot;&quot;,<br>    &quot;row&quot;: &quot;&quot;,<br>    &quot;number&quot;: ...,<br>    &quot;category&quot;: &quot;&quot;,<br>    &quot;status&quot;: &quot;&quot;<br>  },<br>  ...<br>  ],<br>  &quot;pricing&quot;: {<br>   &quot;premium&quot;: {<br>    &quot;price&quot;: 300,<br>    &quot;currency&quot;: &quot;INR&quot;<br>    ...<br>   },<br>   ...<br>  }<br>}<br><br>Status: 404 # Not Found<br>Status: 429 # Too Many Requests</pre><p><strong>Book Show</strong></p><pre>POST /v1/shows/&lt;show_id&gt;/book<br><br>Request<br>{<br> &quot;showId&quot;: &quot;&quot;,<br> &quot;selectedSeats&quot;: [&quot;&quot;, &quot;&quot;, ...],<br> ...<br>}<br><br>Response<br><br>Status: 200 # OK<br>{<br> &quot;booking_id&quot;: &quot;&quot;<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 404 # Not Found<br>Status: 409 # Conflict<br>{<br> &quot;message&quot;: &quot;Some seats are not available.&quot;,<br> &quot;metadata&quot;: {<br>  &quot;seats&quot;: [&quot;&quot;, ...]<br> }<br>}<br>Status: 429 # Too Many Requests</pre><p><strong>Initiate Payment</strong></p><pre>POST /v1/booking/payment?booking_id=&lt;&gt;<br><br>Request<br>{<br> &quot;payment&quot;: {<br>  &quot;method&quot;: ...,<br>  &quot;amount&quot;: {<br>   &quot;total&quot;: ...,<br>   &quot;currency&quot;: &quot;&quot;<br>  }<br>}<br><br>Response<br><br>Status: 302 Found<br>Location: https://payment-gateway.com/checkout/kh351...?return_url=&lt;&gt;&amp;webhook_url=&lt;&gt;<br><br>Status: 401 # Failed User Authentication<br>Status: 404 # Not Found<br>Status: 409 # Conflict<br>Status: 429 # Too Many Requests</pre><blockquote>☢️ Redirection using 302 Status code and 200 Status code with the redirection URLs being passed in the body are both valid approaches. One may prefer 200 Status code if the payment-gateway SDK is integrated in the client-side code and thus sending the parametres individually will make more sense.</blockquote><blockquote>Nevertheless, the key thing here is to:<br>- ensure that details like amount parameters are not passed here (this is because backend will create an order in the payment gateway with required values in advance before returning the redirect URL)<br>- identify the need for sending callback / webhook URLs in the redirected request to allow the payment gateway to revert back on the status of the transaction.</blockquote><p><strong>Payment Status</strong></p><pre>GET /v1/booking/payment/status?booking_id=&lt;&gt;<br><br>Response<br><br>Status: 200 # OK<br>{<br> &quot;bookingId&quot;: &quot;&quot;,<br> &quot;paymentRefId&quot;: &quot;&quot;,<br> &quot;status&quot;: &quot;&quot;,<br> ...<br>}<br>Status: 401 # Failed User Authentication<br>Status: 404 # Not Found<br>Status: 429 # Too Many Requests</pre><p><strong>Payment Webhook</strong></p><pre>POST /v1/api/webhooks/&lt;payment-gateway&gt;<br><br>Request<br><br>{<br> &quot;id&quot;: &quot;&quot;,<br> &quot;eventType&quot;: &quot;&quot;,<br> &quot;resource&quot;: {<br>  &quot;id&quot;: &quot;&quot;,<br>  &quot;status&quot;: &quot;&quot;,<br>  &quot;amount&quot;: {<br>   &quot;total&quot;: ...,<br>   &quot;currency&quot;: &quot;&quot;<br>  },<br>  &quot;externalId&quot;: &quot;&quot;,<br>  &quot;updateTs&quot;: &quot;&quot;<br> }<br>}<br><br>Response<br><br>Status: 200 # OK</pre><blockquote>☢️ Avoid returning client or server errors for webhook endpoints even when there are issues in the webhook being triggered. Instead gracefully handle them in the business logic.</blockquote><p><strong>Cancel Booking</strong></p><pre>POST /v1/booking/cancel?booking_id=&lt;&gt;<br><br>Request<br><br>{<br> &quot;refundMethod&quot;: &quot;&quot;,<br> ...<br>}<br><br>Response<br><br>Status 202 # Accepted<br>{<br> &quot;refundId&quot;: &quot;&quot;,<br> &quot;refundAmount&quot;: {<br>  &quot;total&quot;: ...,<br>  &quot;currency&quot;: &quot;&quot;<br> }<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 404 # Not Found<br>Status: 409 # Conflict<br>Status: 429 # Too Many Requests</pre><p><strong>Get Orders</strong></p><pre>GET /v1/orders?pageSize=10&amp;cursorMark=&lt;&gt;<br><br>Response<br><br>Status: 200 # Succesfully Fetched<br>{<br>  &quot;data&quot;: [<br>   {<br>    &quot;orderId&quot;: &quot;&quot;,<br>    &quot;movieName&quot;: &quot;&quot;,<br>    ...<br>   },<br>   {<br>    ...<br>   },<br>   ...<br>  ],<br>  &quot;pagination&quot;: {<br>  &quot;totalCount&quot;: 7<br>  &quot;nextCursorMark&quot;: &quot;jhik2498&quot;<br>  }<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 429 # Too Many Requests</pre><p><strong>Get Order</strong></p><pre>GET /v1/orders/&lt;order_id&gt;<br><br>Response<br><br>Status: 200 # Succesfully Fetched<br>{<br>  &quot;orderId&quot;: &quot;&quot;,<br>  &quot;movieName&quot;: &quot;&quot;,<br>  ...<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 404 # Not Found<br>Status: 429 # Too Many Requests</pre><blockquote>🔧 Try to implement APIs for managing shows and support blocking/unblocking of seats for a theatre / show by admin users.</blockquote><h3>System Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyQvnDx-1-fbE760o_A2cA.png" /></figure><p><strong>Booking Flow</strong></p><ol><li>User selects the show and the desired seats which are available and proceeds to book the show.</li><li>If the selected seats have already been booked by another user, the API returns with a 409. Client will re-fetch the seat availability and allow the user to place the booking request once again.</li><li>If the selected seats were indeed available, Booking service will create an entry in the Booking table and the associate tickets as RESERVED along with an expiry. This expiry window will usually be shorter (around 2–3 minutes) to allow people to initiate payment.</li><li>If the user proceeds ahead to initiate payment after the expiry, the system tries to extend the expiry for each ticket again, otherwise will throw a 409 asking the user back to re-attempt.</li><li>If the user proceeds ahead to initiate payment in a timely fashion, the system will:<br>- update the Booking table status to PAYMENT_PENDING<br>- update the ticket status to PAYMENT_PENDING along with a longer expiry time<br>- create an order in the payment gateway and return the associated checkout URL back to the user.<br>- schedule an event for reconciliation to handle situations such as no response from payment gateway and thus initiate refund.</li><li>The client will redirect the user to the payment-gateway checkout experience. User will make the payment and gets redirected back to the status page. In parallel, the payment gateway informs the Booking Service via webhook about the payment status which gets updated in the DB followed by a notification to the user.</li></ol><blockquote>☢️ Many candidates might be tempted to use the redirect status URL to mark the payment as successful. Doing this will leave our system in a vulnerable state as malicious users will be able to update the booking status without making an actual payment. As a result the Booking Service should only rely upon status received via webhook or the reconciliation job.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*Mo7T-rRnwVvx7eTz70Umjw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86d7c62e03d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notification System Design]]></title>
            <link>https://medium.com/@parts.of.programming/notification-system-design-d41f21b67304?source=rss-2339a4910d8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d41f21b67304</guid>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Parts Of Programming]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 15:49:04 GMT</pubDate>
            <atom:updated>2025-02-09T15:49:04.360Z</atom:updated>
            <content:encoded><![CDATA[<p>Design a system for delivering various forms of notifications across channels</p><blockquote>💎 Notification systems vary widely in scope and functionality based on their core purpose. When discussing such systems in interviews, collaborate with the interviewer to clearly define the must-have (P0) requirements before proceeding with the design.</blockquote><h3>Functional Requirements</h3><p>A user should be able to:</p><ol><li>choose which channel is disabled for receiving notification — email, whatsapp, messages, etc. (default being enabled)</li></ol><p>System should be able:</p><ol><li>support targetted notifications</li><li>support raw notifications</li><li>support bulk notifications based on user segments</li><li>should be able to differentiate amongst priority (OTP, etc.) and non-priority notifications (marketing campaigns)</li><li>enforce rate limiting</li></ol><p>An admin user should be able to:</p><ol><li>create, update and delete the template for the notification to be sent</li><li>monitor the performance of notifications</li><li>configure how many max retries are made to deliver a notification</li></ol><h4>Anti-goals</h4><ol><li>User segmentation logic is handled by existing service</li><li>Multi-media content storage and management is handled by external system</li></ol><h3>Non-Functional Requirements</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8snDLV9aSWmQaWwXd1N1Q.png" /></figure><h3>Capacity Estimations</h3><p>DAU (in Mn): 100<br>Average Notification/day/user: 10<br>Notification Size (in KB): 1<br>Daily Usage (in TB): 1<br>Monthly Usage (in TB): 30</p><h3>High Level Design</h3><h4>Core Entities</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9_NP95zvwnavi1ufg_rZw.png" /></figure><p><strong>UserNotificationPreferences:</strong> responsible for storing whether a user has explicitly opted-out of a particular channel.</p><p><strong>NotificationTemplate:</strong> contains a templatized version of the content that needs to be delivered as part of the notification.</p><p><strong>MultiMediaContent:</strong> contains references to images, videos that are to be rendered in the notification.</p><p><strong>Notification:</strong> represents a concrete notification to be sent to the end-user holding reference to a particular template</p><p><strong>Notification Variables:</strong> represents variables used by the template which needs to be injected to fully create a notification.</p><p><strong>Delivery:</strong> represents the delivery attempts being made to send a notification annotated with channel_partner_id to uniquely identify which Service Provider was selected.</p><p><strong>Tracking:</strong> represents the outcome of the delivery if the notification was successfully delivered by the service provider and read by the user if applicable.</p><h4>API Interfaces</h4><p><strong><em>Headers</em></strong></p><p>We will use headers for identifying the user. For simplicity, we can use stateless mechanism such as JWT and introduce statefull mechanisms such as OAuth later on as needed.</p><pre>Authorization: Bearer ...</pre><p><strong><em>Create a Notification Template</em></strong></p><pre>POST /v1/notification/template<br><br>{<br> &quot;content&quot;: &quot;&quot;,<br> &quot;multiMedia&quot;: {<br>  &quot;label&quot;: {<br>   &quot;location&quot;: &quot;&quot;<br>  }<br> }<br>}<br><br>Status: 201 # Successfully Created<br>{<br> &quot;id&quot;: &quot;n1&quot;<br>}<br><br>Status: 400 # Failed Validations<br>{<br>   &quot;message&quot;: &quot;&quot;<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 429 # Breaching capacity constraints</pre><p><strong><em>Update a Notification Template</em></strong></p><pre>PUT /v1/notification/template/:id<br><br>{<br> &quot;content&quot;: &quot;&quot;,<br> &quot;multiMedia&quot;: {<br>  &quot;label&quot;: {<br>   &quot;location&quot;: &quot;&quot;<br>  }<br> }<br>}<br><br>Status: 200 # Successfully Updated<br>{<br> &quot;id&quot;: &quot;n1&quot;<br>}<br><br>Status: 400 # Failed Validations<br>{<br>   &quot;message&quot;: &quot;&quot;<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 429 # Breaching capacity constraints</pre><p><strong><em>Delete a Notification Template</em></strong></p><pre>DELETE /v1/notification/template/:id<br><br>Status: 202 # Accepted or Not Found<br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization</pre><blockquote>💎 We choose to use soft deletes by updating the status against a NotificationTemplate in order to avoid failure in deliveries of notifications which are in-flight.</blockquote><p><strong><em>Send a Notification using Template</em></strong></p><pre>POST /v1/notification/send<br><br>{<br> &quot;template&quot;: {<br>  &quot;id&quot;: &quot;n1&quot;,<br>  &quot;version&quot;: 2,<br>  &quot;variables&quot;: {<br>   &quot;label1&quot;: &quot;value1&quot;<br>  }<br> },<br> &quot;user&quot;: {<br>  &quot;id&quot;: &quot;u1&quot;,<br>  &quot;channel&quot;: &quot;email&quot;,<br>  &quot;target&quot;: &quot;u1@email.com&quot;<br> },<br> &quot;instructions&quot;: {<br>  &quot;priority&quot;: 2,<br>  &quot;maxRetries&quot;: 3,<br>  &quot;tracking&quot;: &quot;ATLEAST_ONCE&quot;<br> }<br><br>Status: 202 # Accepted or Not Found<br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 422 # Unable to create notification against deleted templates</pre><p><strong><em>Disable/Enable Notification Channel</em></strong></p><pre>POST /v1/notification/preferences/:channel?action=disable<br><br>Status: 202 # Accepted or Not Found<br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization</pre><h4>System Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5iH2SVoS1txjC0lZfAiKSw.png" /></figure><p><strong>Notification Manager:</strong> responsible for managing the notification templates and maintain user channel preferences. It also serves the read requests for both template and user-preference via a cache-side redis cluster.</p><blockquote>🐬 Potential Deep-Dive: Data Model for Cassandra Tables</blockquote><p><strong>Notification Collector:</strong> responsible for handling the notification delivery requests coming from various backend clients and pushes them to Kafka depending upon the priority assigned to that request.</p><blockquote>🐬 Potential Deep-Dive: How to implement a Distributed Rate Limiter</blockquote><p><strong>Notifcation Consumer — Priority:</strong> reads the notification request from the associated Kafka topic and:</p><ol><li>fetches user preference. If the channel is blocked by the user, it drops the notification</li><li>validates the rate limits for the given channel and user</li><li>fetches the template for the notification and creates a fully-formed message to be sent</li><li>produces the message on to the channel-specific topic.</li></ol><blockquote>❇️ Potential Level-up: Support for atleast-once delivery</blockquote><p>For critical notifications, we may be interested in ensuring that the notification actually got delivered to the end-user by the vendor.</p><p>This can be done by adding delivery_guarantee field in the Notification entity at the data level.</p><p>On the system side, there are two probable solutions:</p><ol><li>polling approach on the Notification Tracker Database.</li><li>using scheduler system to schedule a delayed message. &lt;/aside&gt;</li></ol><p><strong>Email Router — Priority:</strong> responsible for processing the fully-formed notification and identify which service provider to use and invoke their respective APIs.</p><blockquote>🐬 Potential Deep-Dive: How to implement the Load Balancer Strategy for selecting a vendor</blockquote><p><strong>TrackingCollector:</strong> responsible for receiving the callbacks from service provider regarding status of the notifications.</p><p><strong>Tracking Consumer — Priority:</strong> responsible for persisting the information to Tracking Cassandra to identify the failure rates.</p><blockquote>🐬 Potential Deep-Dive: How to implement a Multi-media Content Storage and CDN system</blockquote><h3>Refinements</h3><p><strong><em>Incorporating Bulk Notifications</em></strong></p><p>Bulk Notification use-cases generatlly revolve sending a given notification to a segment of user-base which are conforming to a given critiera. This can be achieved by appending the Bulk Notification Component as a pre-processor to the Notification Collector as shown below.</p><pre>graph LR<br>BN[Bulk Notification] --&gt; Scheduler<br>Scheduler --&gt; K1[Kafka]<br>K1 --&gt; BNF[Bulk Notification Fanout]<br>BNF --&gt; US[User Segmentation]<br>BNF --&gt; K2[Kafka]<br>K2 --&gt; BNP[Bulk Notification Publisher]<br>BNP --&gt; NC[Notification Collector]</pre><blockquote>🐬 Potential Deep-Dive: Data Model for supporting Bulk Notifications</blockquote><p><strong><em>Incorporating Automatic Channel-Selection</em></strong></p><p>In case ServiceX doesn’t specify the channel of choice when requesting to publish a notification, the system should be able to decide which channel to pick amongst the ones available.</p><p>This can be achieved by aggregating analytics around the channel efficiency at a user-level, region-level and platform-level. This coupled with notificaiton’s priority and operational status of the channel can help us decide which to pick.</p><p>Integration with Channel Selector component will need to be done at Notification Consumer to support the correct routing in the downstream.</p><p><strong><em>Incorporating Raw Notifcations</em></strong></p><p>Most use-cases will translate to creating a templatized content agnostic of user and filling the user-specific data at the time of actually sending the notification. This helps us reduce the bandwidth consumption until the time when the system has decided to go ahead with notification delivery. Additionally, it helps managing such templates centrally at one location and avoiding duplication and developing template-level performance via a single window.</p><p>However, in case raw notification support is still expected, we can tweak our data model by adding a separate AdhocNotification entity and handle the logic at application level across Notification Collector and Notification Consumer components with further downstream components remaining agnostic of it.</p><blockquote>❇️ Potential Level-Up: Ask the candidate to support multi-tenancy with billing and reporting features.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d41f21b67304" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scheduling System Design]]></title>
            <link>https://medium.com/@parts.of.programming/scheduling-system-design-a6f0f4dd8a61?source=rss-2339a4910d8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6f0f4dd8a61</guid>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[scheduling-software]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Parts Of Programming]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 17:49:00 GMT</pubDate>
            <atom:updated>2025-02-02T17:49:00.632Z</atom:updated>
            <content:encoded><![CDATA[<p>Design a system for managing and executing scheduled tasks.</p><blockquote>💎 Start with clarifying questions with the goal of determining outlining the functionalities desired.</blockquote><h3>Functional Requirements</h3><p>User should be able to define a schedule:</p><ol><li>type: one-time, recurring</li><li>cron-expression: when should the schedule be running</li><li>validity start: when should the schedule become active</li><li>validity end: when should the schedule become inactive</li><li>retries: how many retries should be done during instance failures</li></ol><p>User should be able to edit, delete and read a schedule</p><blockquote>💎 Take a “very brief” moment to mention some of the good to have advanced features e.g. audit history for schedule, notification based on run status, etc. This is just to demonstrate product-thinking and the ability to forsee the development road-map and your focus to identify what’s P0 and what’s not.</blockquote><h4>Anti-goals</h4><p>The tasks to be executed are considered to be light-weight. For heavy workloads, the scheduler will just invoke triggers and track success/failure of such triggers only. At best it can get receive asynchronous updates on the status of the jobs.</p><blockquote>💎 For complex sub-problems, it is often a good idea to slightly negotiate early on the finer details to simplify things and build a working MVP and then incorporate back the P1 requirements if you have time left on the clock.</blockquote><h3>Non-Functional Requirements</h3><p>In terms of CAP theorem, a Scheduler System will usually lie in the AP Domain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZiXWbquY0R8QgkuuG-8Rw.png" /></figure><blockquote>💎 Defining the above NFRs and calling out the associated assumptions will be key differentiator for candidates targetting Staff and above roles.</blockquote><h3>Capacity Estimations</h3><p>Minimum granularity of schedule: 1 minute<br>Initial number of schedules to be onboarded: 1 million<br>Net number of new schedule per month: 10K</p><blockquote>💎 While many find the ritual of doing these calculations mundane, often times this exercise allows the candidate to demonstrate:</blockquote><blockquote>- their comfort with doing rough estimations and error-free calculations<br>- make realistic assumptions wherever explicit data points are not shared based on their real-world experience<br>- capture insights which will be useful for tech choices as the interview proceeds</blockquote><p><strong><em>Schedule</em></strong></p><p>Bytes per record: 200<br>Initial Size (MB): 200<br>New Records/month: 10,000<br>1M Growth (MB): 2<br>1Y Growth (MB): 24</p><p><strong><em>Executions</em></strong></p><p>Bytes per record: 500<br>Records/schedule/day (Mn): 20<br>1M Growth (GB): 300<br>Monthly Growth Rate: 1.01<br>1Y Growth (TB): 3.8<br>2Y Growth (TB): 8.1</p><blockquote>💎 Callout the following insights:</blockquote><blockquote>- Data for schedules is relatively small and with an average yearly growth we may need not worry about archival or performance issues at this stage.<br>- Data for Executions will grow in an exponential fashion. Moreover the data older than a month might not be required beyond audit or analytics purposes and hence there is valid scope for introducing an archival strategy here.</blockquote><h3>High-Level Design</h3><blockquote>💎 We can start defining entities in an ER model, and assume to store things in an RDBMS. But remember to verbally callout the need review this decision later, especially around the NFRs.</blockquote><blockquote>This methodology helps us deliver a workable MVP solution faster and leaves room for refinements subsequently after.</blockquote><h4>Core Entities</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*R9E1VgHDxy1F_iEvKxgYYA.png" /></figure><p><strong>Schedule</strong>: responsible for storing the core definition of the schedule.</p><blockquote>💎 Most candidates usually start with a single table coagulating the schedule definition, monitor and the executions. By structuring the schema in a normalized fashion we end up achieving separation of concerns, scalability and better fault tolerance.</blockquote><p><strong>Job</strong>: contains the information regarding actual job to be executed. For now we have assumed that it will be an API call and left out the finer details — such as support for template variables in the API call, authorization tokens, etc.</p><blockquote>☢️ There is an alternative approach of using raw binaries (such as docker images, scripts etc.) here. If in case, you wish to go that route ensure that you are prepared to handle the potential deep-dive into the sub-domain. If you are under confident, it is probably a good idea to steer clear from binaries and introduce system constraints around Job definition (HTTP call or a message in the Queue)</blockquote><p><strong>Monitor</strong>: This table is the main query table to determine what job to execute during each window.</p><p><strong>Execution</strong>: When a monitor identifies a job needs to be executed, it will create an entry in the execution table and prepare itself to be ready for the next iteration. This will be especially critical for high frequency jobs if they face any retry attempts leading to overlaps.</p><p><strong>Run</strong>: An execution may need multiple attempts to get successfully executed. Such individual attempts will be explicitly tracked here.</p><blockquote>❇️ Potential Level-Up: Ask the candidate to support retries with back-offs.</blockquote><h4>API Interfaces</h4><p><strong><em>Headers</em></strong></p><p>We will use headers for identifying the user. For simplicity, we can use stateless mechanism such as JWT and introduce statefull mechanisms such as OAuth later on as needed.</p><p>Authorization: Bearer: ...</p><blockquote>💎 For senior candidates it is critical to demonstrate their tech-depth by highlighting the trade-off made around using security aspect here.</blockquote><p><strong><em>Create Schedule</em></strong></p><pre>POST /v1/scheduler<br><br>{<br> &quot;name&quot;: &quot;&quot;,<br> &quot;recurrence&quot;: &quot;&quot;,<br> &quot;cronExpression&quot;: &quot;&quot;,<br> &quot;validity&quot;: {<br>  &quot;startTs&quot;: &quot;&quot;,<br>  &quot;endTs&quot;: &quot;&quot;<br> },<br> &quot;retries&quot;: {<br>  &quot;maxCount&quot;: 1<br> }<br> ...<br>}<br><br>Status: 201 # Succesfully Created<br>{<br> &quot;id&quot;: &quot;s1&quot;<br>}<br><br>Status: 400 # Failed Validations<br>{<br>   &quot;message&quot;: &quot;&quot;<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 429 # Breaching capacity constraints</pre><p><strong><em>View a Schedule</em></strong></p><pre>GET /v1/scheduler/:schedule_id<br><br>Status: 200 # Succesfully Fetched<br>{<br> &quot;id&quot;: &quot;&quot;,<br> ...,<br> &quot;job&quot;: {<br>  &quot;&quot;,<br> }<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 404 # Not Found<br>Status: 429 # Too Many Requests</pre><p><strong><em>Update a Schedule</em></strong></p><pre>PATCH /v1/scheduler/:schedule_id <br><br>{<br> &quot;id&quot;: &quot;s1&quot;,<br> &quot;cronExpression&quot;: &quot;&quot;<br>}<br><br>Status: 202 # Accepted<br><br>Status: 400 # Failed Validations<br>{<br>   &quot;message&quot;: &quot;&quot;<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 404 # Not Found</pre><p><strong><em>Active/Deactivate Schedule</em></strong></p><pre>POST /v1/scheduler/:schedule_id?action=activate <br><br>Status: 202 # Accepted<br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 404 # Not Found</pre><p><strong><em>Delete a Schedule</em></strong></p><pre>DELETE /v1/scheduler/:schedule_id<br><br>Status: 202 # Accepted or Not Found<br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization</pre><p><strong><em>View top 10 schedules to be executed</em></strong></p><pre>GET /v1/scheduler?pageSize=10&amp;sortBy=earliest<br><br>Status: 200 # Succesfully Fetched<br><br>{<br> &quot;data&quot;: [<br>  {<br>   &quot;id&quot;: &quot;s1&quot;,<br>   ...<br>  },<br>  {<br>   &quot;id&quot;: &quot;s2&quot;,<br>   ...<br>  }<br> ],<br> &quot;pagination&quot;: {<br>  &quot;totalCount&quot;: 173<br>  &quot;nextCursorMark&quot;: &quot;e34hk3kn&quot;<br> }<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 404 # Not Found<br>Status: 429 # Too Many Requests</pre><p><strong><em>View Executions</em></strong></p><pre>GET /v1/scheduler/:schedule_id/executions?sortBy=latest&amp;pageSize=10 <br><br>Status: 200 # Succesfully Fetched<br>{<br> &quot;data&quot;: [<br>  {<br>   &quot;id&quot;: &quot;&quot;,<br>   ...<br>  },<br>  {<br>   &quot;id&quot;: &quot;&quot;,<br>   ...<br>  }<br> ],<br> &quot;pagination&quot;: {<br>  &quot;totalCount&quot;: 173<br>  &quot;nextCursorMark&quot;: &quot;e34hk3kn&quot;<br> }<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 404 # Not Found<br>Status: 429 # Too Many Requests</pre><p><strong><em>View Runs for an Execution</em></strong></p><pre>GET /v1/scheduler/:schedule_id/executions/:execution_id/runs?sortBy=latest<br><br>Status: 200 # Succesfully Fetched<br>{<br> &quot;data&quot;: [<br>  {<br>   &quot;id&quot;: &quot;&quot;,<br>   ...<br>  },<br>  {<br>   &quot;id&quot;: &quot;&quot;,<br>   ...<br>  }<br> ],<br> &quot;pagination&quot;: {<br>  &quot;totalCount&quot;: 173<br>  &quot;nextCursorMark&quot;: &quot;e34hk3kn&quot;<br> }<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 404 # Not Found<br>Status: 429 # Too Many Requests</pre><p><strong><em>View Run Info</em></strong></p><pre>GET /v1/scheduler/:schedule_id/executions/:execution_id/runs/:run_id<br><br>Status: 200 # Succesfully Fetched<br>{<br> &quot;id&quot;: &quot;&quot;,<br> ...<br>}<br><br>Status: 401 # Failed User Authentication<br>Status: 403 # Failed User Authorization<br>Status: 404 # Not Found<br>Status: 429 # Too Many Requests</pre><blockquote>💎 While Protobuf, GraphQL, Avro, etc. has gained popularity in the recent times, it is often still a safer decision to stick to ReST in most cases. You can however callout the need to use X or Y option as the case maybe as applicable.</blockquote><h4>System Diagram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fKsZLkhvbXe4xAphuzJdzw.png" /></figure><p>User interacts with Scheduler for managing schedule definitions. Scheduler updates the definition in Schedule and Job Table and communicates with Supervisor via Kafka topic SCHEDULE_UPDATES.</p><p>Supervisor updates the Monitor basis the SCHEDULE_UPDATES message if the next_execution_ts is impacted.</p><p>Additionally, it checks for jobs which needs to be executed every minute and publishes those to another Kafka topic JOB_EXECUTION and updates the next_execution_ts to reflect the next trigger, if applicable based on Schedule status.</p><p>Executor reads JOB_EXECUTION (and JOB_EXECUTION_RETRY) message and updates Execution and Run table accordingly. In case of failures and retry being applicable, it emits a message to JOB_EXECUTION_RETRY topic.</p><p>If a job has maxed out its retries, Executor can potentially publish a message in a Dead Letter Queue for active tracking of such failures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lF9DXbdPG8hOc31aaEe_w.png" /><figcaption>Schedule State Machine</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o07qrgFEYdHNPWVGMRQsGg.png" /><figcaption>Execution State Machine</figcaption></figure><h4>Refinements</h4><p><strong><em>Incorporating High Availability</em></strong></p><p>We can setup a master-slave replication in Mysql. In case master node fails, we can perform failover to a new master.</p><p><strong><em>Incorporating Horizontally Scalability</em></strong></p><p>This can be achieved by using a hashing strategy to distribute schedule_id amongst segments. Introduce segment column in Monitor table and assingn these segments across various Supervisor nodes. A futher improvement will be to move this table to Cassandra or ScyllaDB.</p><blockquote>❇️ Potential Level-Up: Ask the candidate to support multi-tenancy with billing and reporting features.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6f0f4dd8a61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algo-recipes: Russian Peasant]]></title>
            <link>https://medium.com/@parts.of.programming/algo-recipes-russian-peasant-6cbf2b1331f7?source=rss-2339a4910d8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cbf2b1331f7</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Parts Of Programming]]></dc:creator>
            <pubDate>Mon, 02 Oct 2023 07:34:16 GMT</pubDate>
            <atom:updated>2023-10-02T07:45:56.521Z</atom:updated>
            <content:encoded><![CDATA[<p>This algorithm caters to multiplication of two numbers by repeating limited set of operations to achieve the desired result.</p><p>The foundation of this algorithm lies in leveraging the binary representation. There are two common implementations of this algorithm.</p><h3>Implementation</h3><h4>Multiplication of numbers</h4><p>The below function attempts to multiply two numbers by just using the following language semantics — bitwise operation (for parity check), multiplication and division by 2 and in-place addition.</p><pre>def is_odd(num: int):<br>    return num &amp; 1 == 1<br><br>def rp_mul(a: int, b: int):<br>    res = 0<br>    while b &gt; 0:<br>        if is_odd(b):<br>            res += a<br>        a *= 2<br>        b //= 2<br>    return res</pre><h4>Exponentiate a number</h4><p>To exponentiate a number the below logic leverages the idea to use already computed results to save on the overall running time.</p><pre>def rp_exp(num: int, pow: int):<br>    while not is_odd(pow):<br>        num *= num<br>        pow //= 2<br>    res = num<br>    pow //= 2<br>    while pow &gt; 0:<br>        num *= num<br>        if is_odd(pow):<br>            res *= num<br>        pow //= 2<br>    return res</pre><p>Following shows the dry run for rp_exp(3, 13) case</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*UxZBzDSO-K5Z9jlELn4cEg.png" /><figcaption>Dry-run of rp_exp(3, 13)</figcaption></figure><p>Notice how the additions made to `res` variable represents the binary representation of 13 depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*oUOA1wM826qE2hkO21BQfw.png" /><figcaption>Binary Representation of 13</figcaption></figure><h3>Conclusion</h3><p>Russian peasant is a nifty way to implement fundamental operations involving multiplication using the underlying idea of binary representation and leveraging already computed result. Full source code can be found <a href="https://github.com/pop-series/pop-fundamentals/blob/master/py_dsa/algorithm/arithmetic/russian_peasant.py">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cbf2b1331f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical-Recipes: Using ExternalFileField with Apache SolrCloud]]></title>
            <link>https://medium.com/@parts.of.programming/practical-recipes-apache-solrcloud-external-file-field-a2d4091e36ce?source=rss-2339a4910d8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2d4091e36ce</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[apache-solr]]></category>
            <category><![CDATA[solr-cloud]]></category>
            <category><![CDATA[pop-series]]></category>
            <category><![CDATA[sorting]]></category>
            <dc:creator><![CDATA[Parts Of Programming]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 10:42:18 GMT</pubDate>
            <atom:updated>2023-07-14T13:57:58.530Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://solr.apache.org/">Apache Solr</a> is a Lucene-based open-source search platform commonly used in enterprises for powering their SERP, autosuggest, recommendations and/or geospatial search. It is built in Java, but exposes a ReST API as an interface thus allowing it to used with other programming languages as well. This recipe is focussed on using <a href="https://solr.apache.org/guide/solr/latest/indexing-guide/external-files-processes.html">ExternalFileField</a> (a.k.a eff) feature with SolrCloud to efficiently write periodically bulk-updated sort-only fields.</p><h3>Motivation</h3><p>In an enterprise search solution, one of the key requirements is to incorporate a feedback loop based on user-interactions on the platform (clicks, impressions, loads, etc.) and use the derived results to influence the ranking of the result-set over-time. This pertains to introducing a field in the solr index, let’s say “popularity” which will then be used as one of the scores in the scoring formulation and/or as a tie-breaker sort field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXMJGB0u7xr7cLEqAh9Lcg.png" /><figcaption>Figure 1. Updating sort-only fields in SolrCloud</figcaption></figure><p>The major challenges that arises with this field is that a large number of documents will get updated in a pre-defined stipulated time-frame, let’s say every 1hr, which will lead to a large write throughput on solr if we try to index the changes on the go or even in batches (strategy “1” in the Figure 1). This can not just create lag on the indexing pipeline but also negatively impact the read performance by consuming compute resources and degrading solr/lucene internal cache performance.</p><h3>Inspiration</h3><p>Luckily enough, this is not a new problem and Solr already has a solve called <a href="https://solr.apache.org/guide/solr/latest/indexing-guide/external-files-processes.html">ExternalFileField</a> for it. This involves separating out the field from the lucene-index and allowing it to be governed by an External File which can be updated collectively at once (strategy “2” in the Figure 1) thereby reducing the write throughput on solr. One caveat though (as pointed by Mats Lindh in SO <a href="https://stackoverflow.com/a/51547977/6687477">here</a>) that this feature is more suited to Solr Standalone installations and doesn’t play well with SolrCloud out-of-the-box (OOTB). The below section covers the necessary tweaks required to be able to use this feature with SolrCloud seamlessly.</p><h3>Solution</h3><h4>Schema Changes</h4><p>This requires declaring a new field type in solr which will allow it to handle the field differently than other lucene-backed fields. This is usually done by adding the following line in your managed-schema.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;<br>&lt;schema name=&quot;eff-config&quot; version=&quot;1.6&quot;&gt;<br>  ...<br>  &lt;field name=&quot;popularity&quot; type=&quot;extIdMap&quot;/&gt;<br>  ...<br>  &lt;!-- field type definitions --&gt;<br>  ...<br>  &lt;fieldType name=&quot;extIdMap&quot; keyField=&quot;id&quot; defVal=&quot;0&quot; stored=&quot;false&quot; indexed=&quot;false&quot; class=&quot;solr.ExternalFileField&quot;/&gt;<br>  ...<br>&lt;/schema&gt;</pre><p>Note that there are no special constraints on keyField and it may be a non-unique field as well.</p><h4>Uploading Config Changes</h4><p>Once schema changes are done, the same can be uploaded to the zookeeper via the upconfig command which is a pretty standard process</p><pre>./server/scripts/cloud-scripts/zkcli.sh -z ${TARGET_ZK} -cmd upconfig -confdir ${CONF_DIR} -confname ${TARGET_CONF_NAME}</pre><p>In order for the changes to come into affect, the reload API needs to be invoked:</p><pre>curl -i &quot;localhost:8983/solr/admin/collections?action=RELOAD&amp;name=eff_recipe&amp;wt=json&quot;</pre><h4>Preparing Mappings File</h4><p>The mapping file which contains the actual score data needs to be prepared in the following format. To get the best performance recommendation is to ensure that entries are present in sorted order by keyField.</p><pre>book_0=430.16<br>book_1=868.12<br>book_2=601.34<br>book_3=604.64<br>book_4=784.07</pre><p>In order to play around with sample docs and corresponding external file field mapping file, you may refer to the following script: <a href="https://github.com/pop-series/pop-solr/blob/main/practical-recipes/eff/scripts/control.sh">https://github.com/pop-series/pop-solr/blob/main/practical-recipes/eff/scripts/control.sh</a></p><h4>Upload and (Re-)Load Mappings File</h4><p>Since ExternalFileField isn’t solr cluster aware, we will need to explicitly incorporate steps to upload file, replicate, refresh and reload.</p><p>The following section presents an externally-managed solution to achieve the same. However, the same can be automated via different ways which will be covered in a separate post.</p><p>Solr provides a variety of ways to tweak the behavior, one of the ways we can inform solr to download/refresh the contents from an external source is by introducing a custom RequestHandler, ManageEffRequestHandler, which can be invoked for a given core on-demand. For the current example we chose raw.githubusercontent.com itself, but you may implement your own copy of the request handler and integrate with Azure Blob, S3 bucket, GCS or other storage service providers depending upon your use-case.</p><p>In addition we will need to integrate ExternalFileFieldReloader listener with “newSearcher” and “firstSearcher” events so that solr’s in-memory data-structures can be directed to refresh on hitting reload collection API after the local file has been placed.</p><p>Refer the solrconfig.xml given below to understand the corresponding config changes required to enable the same.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;<br>&lt;!--<br>     For more details about configurations options that may appear in<br>     this file, see https://solr.apache.org/guide/solr/latest/configuration-guide/configuring-solrconfig-xml.html.<br>--&gt;<br>&lt;config&gt;<br>  &lt;luceneMatchVersion&gt;9.4&lt;/luceneMatchVersion&gt;<br>  ...<br>  &lt;query&gt;<br>    ...<br>    &lt;listener event=&quot;newSearcher&quot; class=&quot;org.apache.solr.schema.ExternalFileFieldReloader&quot;/&gt;<br>    &lt;listener event=&quot;firstSearcher&quot; class=&quot;org.apache.solr.schema.ExternalFileFieldReloader&quot;/&gt;<br>  &lt;/query&gt;<br>  &lt;requestHandler name=&quot;/manage/eff&quot; class=&quot;io.pop.solr.recipes.eff.ManageEffRequestHandler&quot; startup=&quot;lazy&quot;&gt;<br>    &lt;lst name=&quot;invariants&quot;&gt;<br>      &lt;str name=&quot;downloadLocation&quot;&gt;https://raw.githubusercontent.com/pop-series/pop-solr/main/practical-recipes/eff/sample&lt;/str&gt;<br>    &lt;/lst&gt;<br>  &lt;/requestHandler&gt;<br>&lt;/config&gt;</pre><p>For uploading/refreshing the mappings file, invoke:</p><pre>curl -i &quot;localhost:8983/solr/eff_recipe/manage/eff?fieldName=popularity&amp;sourceFileName=external_popularity_sample.csv&amp;targetFileName=external_popularity.csv.1&quot;</pre><p>Subsequently, invoke the reload API to update in-memory data structure:</p><pre>curl -i &quot;localhost:8983/solr/admin/collections?action=RELOAD&amp;name=eff_recipe&amp;wt=json&quot;</pre><p>Additionally, whenever a new replica is added to the cluster, care needs to be taken to trigger the above steps since IndexFetcher, the class that holds the logic for index replication in solr cloud isn’t ExternalFileField aware.</p><p>The above steps can be easily automated by leveraging the cluster status API <a href="http://localhost:8983/solr/admin/collections?action=CLUSTERSTATUS&amp;name=eff_recipe">http://localhost:8983/solr/admin/collections?action=CLUSTERSTATUS&amp;name=eff_recipe</a> to get the list of all cores, call /manage/eff API for all of them and then lastly trigger collection reload.</p><h4>Possible Integration Improvements</h4><p>The above solution allows the feature to run with SolrCloud though with the following callouts:</p><ol><li>Need to manage failure scenarios with file re-load. If in case one of the cores failed to download the file, it can leave the cluster behavior in an inconsistent state as one or more cores may be missing the mapping or may be on the older version of it</li><li>As more versions are uploaded or a field becomes deprecated or removed, it would be good to clean-up the corresponding mapping file automatically.</li><li>Since the Cache used by FileFloatSource doesn’t extend from CaffeineCache, it lacks the OOTB monitoring facility provided by solr for monitoring cache metrics.</li></ol><h3>Summary</h3><p>In this post we covered how to use ExternalFileField to optimally index sort-only fields which change often for a large number of documents than other fields. We also covered tweaks that will be required to use it with SolrCloud and the associated caveats. The relevant code is available at the below link.</p><p><a href="https://github.com/pop-series/pop-solr/tree/main/practical-recipes/eff">pop-solr/practical-recipes/eff at main · pop-series/pop-solr</a></p><p>Do check it out and highlight any improvements that you come across. If you found this blog and the repository useful, please hit the clap/star button to motivate us to produce more such content.</p><p>In the next post, we will cover in detail about the solr internals which power the ExternalFileField, how we can make Index Replication in solr cloud truly eff-aware and read/write performance benchmarks comparing them with normal lucene-backed sort-only fields.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2d4091e36ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical-Recipes: Using Dependency Injection in Apache-Storm]]></title>
            <link>https://medium.com/@parts.of.programming/practical-recipes-apache-storm-spring-chapter-8118cc44e398?source=rss-2339a4910d8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8118cc44e398</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[apache-storm]]></category>
            <category><![CDATA[real-time-processing]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Parts Of Programming]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 13:01:47 GMT</pubDate>
            <atom:updated>2023-07-24T07:43:28.090Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://storm.apache.org/">Apache Storm</a> is an open source distributed realtime task computation system. It provides a convenient way to process incoming streams of data, transform them and reliably store them in the relevant sink layer. It is primarily used in Java ecosystem, but <a href="https://storm.apache.org/releases/2.4.0/Multilang-protocol.html">extensions</a> exist in other languages too such as python, ruby and javascript. This blog post is concerned about Storm’s use in java ecosystem and how to combine it with popular <a href="https://en.wikipedia.org/wiki/Dependency_injection">Dependency Injection</a> (DI) container providers such as <a href="https://github.com/spring-projects/spring-framework">Spring</a> to create maintainable and robust pipelines.</p><h3>Motivation</h3><p>An enterprise-level storm application projects usually involves multiple bolts/spouts (collectively referred to as tasks in Storm’s parlance) dealing with a set of shared dependencies, e.g. an upstream api client, a database client, rate-limiter registry, circuit breaker registry, etc which needs to be instantiated once in the entire lifecyle. Additionally, Storm task management and lifecyle presents two challenges:</p><ol><li>tasks in a Storm topology can be serialized and sent to more than one worker node as per the topology configuration topology.workers.</li><li>members of an object which are not serializable can’t be instantiated until the respective init method is called (open for spouts and prepare for bolts).</li></ol><p>This often results into singelton patterns seeping into the code base. Moreover, these classes need to become responsible for the following in addition to their core responsibility:</p><ol><li>managing all the input configs required for creating their dependencies</li><li>managing the same for cascaded dependencies</li><li>ensuring that all the relevant dependencies are initialized and injected in the prepare method.</li></ol><pre>// Shared class<br>public class SentenceTranslator implements SentenceTransformer {<br>  public record Config(String targetHost, int targetPort) {}<br><br>  private static Map&lt;Config, SentenceTranslator&gt; instanceMap = new HashMap&lt;&gt;();<br><br>  private final HttpClient client;<br><br>  @VisibleForTesting<br>  SentenceTranslator(final Config config) {<br>    ...<br>  }<br><br>  @Override<br>  public String apply(String s) {<br>    ...<br>  }<br><br>  public static synchronized SentenceTranslator getInstance(final Config config) {<br>    return instanceMap.computeIfAbsent(config, key -&gt; new SentenceTranslator(key));<br>  }<br><br>  @VisibleForTesting<br>  static synchronized SentenceTranslator setInstance(<br>      final Config config, final SentenceTranslator givenInstance) {<br>    return instanceMap.put(config, givenInstance);<br>  }<br>}</pre><pre>// Bolt class<br>public class TastelessTransformerBolt extends BaseTickTupleAwareRichBolt {<br>  ...<br><br>  @Setter(AccessLevel.PACKAGE) // visible for testing<br>  private transient SentenceTransformer sentenceTransformer;<br><br>  ...<br><br>  @Override<br>  public void prepare(<br>      Map&lt;String, Object&gt; topoConf, TopologyContext context, OutputCollector collector) {<br>    this.collector = collector;<br>    if (sentenceTransformer != null) {<br>      final String translatorHost = (String) topoConf.get(Constants.TRANSLATOR_HOST_CONFIG_KEY);<br>      final int translatorPort = (int) topoConf.get(Constants.TRANSLATOR_PORT_CONFIG_KEY);<br>      sentenceTransformer =<br>          SentenceTranslator.getInstance(<br>              new SentenceTranslator.Config(translatorHost, translatorPort));<br>    }<br>  }<br><br>  ...<br>}</pre><p>These challenges are not peculiar to a Storm application and using DI technique is a wide-known solution to circumvent this, with Spring being one of the popular providers of DI in Java (along with <a href="https://github.com/google/guice">Guice</a> and <a href="https://dagger.dev/">Dagger 2</a>). However, this required figuring out a way to allow instantiation of a worker level context independent of the aforementioned init methods at task level.</p><h3>Inspiration</h3><p>And the inspiration came from a <a href="https://stackoverflow.com/a/50161858">StackOverflow answer</a> written by Stig Rohde Døssing, who is one of the <a href="https://github.com/apache/storm#committers">committers</a> on the Storm project where he mentions about leveraging <a href="https://storm.apache.org/releases/1.2.4/Hooks.html">WorkerHook lifecycle</a> methods to manage application-level context. (ref: <a href="https://issues.apache.org/jira/browse/STORM-126">https://issues.apache.org/jira/browse/STORM-126</a>)</p><p>Still, any DI framework can only manage beans/objects that it creates by itself. Dependencies for objects created outside of its container will still need to be explicitly managed though. This means that we will need to integrate the init methods of tasks (which are constructed by Storm) with the spring bean factory and inject their direct dependencies. This is a bit of an inconvenience, however it helps remove the burden of knowing how to “create” the dependency and be totally “agnostic of cascaded dependencies”, which collectively is a major improvement.</p><h3>Solution</h3><figure><img alt="Spring Integration in Storm Topology using Worker Hooks" src="https://cdn-images-1.medium.com/max/1024/1*AkqqAouRrm6ktuaq3-qz8A.png" /><figcaption>Spring Integration in Storm Topology using Worker Hooks</figcaption></figure><h4><strong>Instantiating Spring Context in a custom WorkerHook</strong></h4><p>While Spring beans can be declared using Java configuration itself, it is often a better idea for applications such as Storm to externalize this either into a separate Java project or using external declaration formats such as XML or groovy. This helps in keeping the common building blocks together and packaged into a fat-jar once and use-case specific configurations — topology definition and bean definition into a separate project which may need to be tweaked and configured as per environment.</p><pre>public class SpringAwareWorkerHook extends BaseWorkerHook {<br><br>  private final String[] springConfigLocations;<br><br>  private transient ConfigurableApplicationContext springContext;<br><br>  public SpringAwareWorkerHook(final String[] springConfigLocations) {<br>    super();<br>    this.springConfigLocations = springConfigLocations;<br>  }<br><br>  @Override<br>  public void start(Map&lt;String, Object&gt; topoConf, WorkerTopologyContext context) {<br>    super.start(topoConf, context);<br>    springContext = new ClassPathXmlApplicationContext(springConfigLocations);<br>    // TODO: make the spring context accessible to tasks<br>    log.info(&quot;spring context initialized: [{}]&quot;, springContext);<br>  }<br><br>  @Override<br>  public void shutdown() {<br>    super.shutdown();<br>    if (springContext != null) {<br>      springContext.close();<br>    }<br>  }<br>}</pre><h4><strong>Injecting direct dependencies of tasks</strong></h4><p>While instantiating the spring context in the worker hook appeared straightforward, making it available to tasks appeared tricky. Digging into the Storm code-base and open JIRA tickets helped in discovering TopologyContext#getResource(String) method whose wiring seems to be broken (ref: <a href="https://issues.apache.org/jira/browse/STORM-172">https://issues.apache.org/jira/browse/STORM-172</a>). As a result the only short-term measure that we have was to again fall-back on static variables while ensuring the code remains unit-testable as best as we can.</p><pre>public class BeanFactoryProvider {<br><br>  @Getter<br>  @Setter(AccessLevel.PACKAGE)<br>  private static BeanFactory factory;<br>}</pre><pre>public class SpringAwareWorkerHook extends BaseWorkerHook {<br>  ...<br>  @Override<br>  public void start(Map&lt;String, Object&gt; topoConf, WorkerTopologyContext context) {<br>    ...<br>    BeanFactoryProvider.setFactory(springContext);<br>    ...<br>  }<br>  ...<br>}</pre><pre>public class WordExtractorBolt extends BaseTickTupleAwareRichBolt {<br><br>  private final String wordExtractorBeanRef;<br>  private transient OutputCollector collector;<br>  private transient WordExtractor wordExtractor;<br><br>  @Setter // visible for testing<br>  private transient BeanFactory beanFactory;<br><br>  ...<br>  @Override<br>  public void prepare(<br>      Map&lt;String, Object&gt; topoConf, TopologyContext context, OutputCollector collector) {<br>    this.collector = collector;<br>    if (beanFactory == null) {<br>      beanFactory = BeanFactoryProvider.getFactory();<br>    }<br>    wordExtractor = beanFactory.getBean(wordExtractorBeanRef, WordExtractor.class);<br>  }<br><br>  ...<br>}</pre><p>However, a PR has already been submitted to allow Worker Hooks to set user resources in the official Storm github repository: <a href="https://github.com/apache/storm/pull/3547">https://github.com/apache/storm/pull/3547</a></p><h4>Declaring WorkerHook in the topology definition</h4><p>Storm provides two ways for declaring topology definitions — <a href="https://storm.apache.org/releases/current/Tutorial.html#a-simple-topology">Java-based</a> using TopologyBuilder and <a href="https://storm.apache.org/releases/current/flux.html">Yaml-based</a> using Flux.</p><p>In case of Java-based, the TopologyBuilder#addWorkerHook can be used to configure the relevant worker hook as shown below.</p><pre>public class TopologyRunner {<br>  ...<br>  public static StormTopology getWordTopology() {<br>    TopologyBuilder builder = new TopologyBuilder();<br><br>    builder.addWorkerHook(new SpringAwareWorkerHook(new String[] {&quot;storm-spring.xml&quot;}));<br>    ...<br><br>    return builder.createTopology();<br>  }<br>}</pre><p>In case of Yaml-based, there was no mention about worker hooks in the relevant documentation about Flux. Digging further, we identified that the declaration for worker hooks is missing in <a href="https://storm.apache.org/releases/current/javadocs/org/apache/storm/flux/model/TopologyDef.html">TopologyDef</a> class which is used to parse the submitted yaml file and this was further confirmed by the following quote on the aforementioned Worker Hooks JIRA (<a href="https://issues.apache.org/jira/browse/STORM-126">https://issues.apache.org/jira/browse/STORM-126</a>)</p><blockquote>I think for the first go it’s ok to make this a Java-only feature by adding something like “4: list&lt;binary&gt; worker_hooks” to the StormTopology structure (where the “binary” refers to a Java-serialized object).</blockquote><p>Likewise, in the last case, a PR to allow adding worker hooks in Flux yaml topology definitions have been submitted: <a href="https://github.com/apache/storm/pull/3546">https://github.com/apache/storm/pull/3546</a></p><h3>Summary</h3><p>In this post we covered how to integrate Spring’s DI capabilities with Storm and the subsequent benefits that can be reaped by doing so. The relevant code is available at: <a href="https://github.com/pop-series/pop-storm/tree/main/practical-recipes">https://github.com/pop-series/pop-storm/tree/main/practical-recipes</a>. Do check it out and highlight improvements. As already listed above minor improvement PRs have already been submitted to official Storm github repositories to add the missing functionalities. Until that gets merged and released, the only option is to either work around those limitations as stated above or prepare a custom jar by cherry-picking the changes onto you relevant version tag.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8118cc44e398" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>