<?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 Sanjiv Singh on Medium]]></title>
        <description><![CDATA[Stories by Sanjiv Singh on Medium]]></description>
        <link>https://medium.com/@singh.sanjiv?source=rss-30311cf4ee3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*YKHhUrg6zvaEC5FN</url>
            <title>Stories by Sanjiv Singh on Medium</title>
            <link>https://medium.com/@singh.sanjiv?source=rss-30311cf4ee3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 17:17:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@singh.sanjiv/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[From Scattered Documents to Instant Answers: Building an AI-Powered Knowledge Library on Snowflake]]></title>
            <link>https://medium.com/@singh.sanjiv/from-scattered-documents-to-instant-answers-building-an-ai-powered-knowledge-library-on-snowflake-6d8275141861?source=rss-30311cf4ee3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d8275141861</guid>
            <category><![CDATA[snowflake-cortex]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[knowledge-management]]></category>
            <dc:creator><![CDATA[Sanjiv Singh]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 14:35:56 GMT</pubDate>
            <atom:updated>2026-07-31T14:35:56.369Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What if you could just <em>ask</em> your company’s documents a question — and get a real answer in seconds?</strong></p><p>“Show me the reference architecture we used for that large-scale Teradata migration last year.” “What automation assets did the team build for the healthcare client?” “Find me the estimation template from the Q3 data platform proposal.”</p><p>No more digging through Box folders, scrolling through Git repos, or pinging five people on Slack. Just ask, in plain English, and get answers with the source documents to back them up.</p><p>That’s what we’re building: an <strong>Organization Asset Library</strong> powered by Snowflake. A natural language interface over your company’s collective knowledge — RFPs, SOWs, architecture docs, research papers, estimation spreadsheets, and code repositories. One place. One question. Instant answers.</p><blockquote><strong>A note before you dive in:</strong> This isn’t a weekend demo or a proof-of-concept tutorial. This is a complete enterprise-grade architecture — covering security, governance, access control, observability, cost monitoring, automated quality evaluation, and production scaling. It’s a longer read. Pour a coffee, bookmark it, and take your time. By the end, you’ll have a full blueprint for building this in your organization — not just the happy path, but the hard parts too.</blockquote><p>Let’s build it layer by layer.</p><h4>The Problem: Your Organization’s Knowledge Is Hard to Find</h4><p>Every organization generates knowledge. A lot of it. Architecture decision records. Migration runbooks. Cost estimation spreadsheets. Design documents. Technical proposals. Design patterns.</p><p>The problem isn’t that this knowledge doesn’t exist. It’s that nobody can find it when they need it.</p><p>Where does it all end up?</p><ul><li><strong>Box/Google Drive</strong> — Nested folders nobody remembers creating</li><li><strong>Git repositories</strong> — Thousands of files, most never read after the project ends</li><li><strong>SharePoint</strong> — The digital equivalent of a filing cabinet in a locked basement</li><li><strong>People’s heads</strong> — The worst single point of failure in any organization</li></ul><p>The result? Teams re-invent solutions that already exist. New hires spend weeks hunting for context. Senior consultants spend their time answering the same questions over and over instead of doing higher-value work.</p><p><strong>The real cost isn’t storage. It’s wasted time, duplicated effort, and institutional knowledge that walks out the door.</strong></p><h4>The Solution: A Natural Language Asset Library on Snowflake</h4><p>The system is built in eight layers, each with a clear job:</p><ul><li><strong>Source Systems</strong> — Your documents live in Box, Google Drive, Git, and S3. Nothing moves.</li><li><strong>Ingestion</strong> — Snowflake connects to those sources, tracks what’s new, and only reprocesses what’s changed.</li><li><strong>Processing</strong> — Documents are parsed, split into meaningful pieces, and automatically tagged by topic and sensitivity level.</li><li><strong>Search</strong> — A managed search engine finds the most relevant pieces using both keyword matching and semantic understanding.</li><li><strong>Agent</strong> — An AI assistant reads those pieces and writes a plain-language answer, with citations.</li><li><strong>Interface</strong> — A web app your team can open in a browser and start asking questions immediately.</li><li><strong>Governance</strong> — Access controls ensure people only see documents they’re allowed to see.</li><li><strong>Monitoring</strong> — Usage logs and cost dashboards keep the system healthy and the budget visible.</li></ul><p>Here’s how they stack together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QSsP-rEkqQgGg2ACA6kz3Q.png" /><figcaption>Figure 1 : Layer Architecture (Image credit : Author)</figcaption></figure><p>Let’s walk through each layer. I’ll challenge the design choices as we go — because that’s how you build something that actually works in production, not just in a demo.</p><h3>Layer 1: Connecting Your Document Sources</h3><blockquote><strong><em>Business impact:</em></strong><em> Stop paying people to re-create assets that already exist. Every document uploaded once becomes findable by everyone — automatically, with zero manual filing. Your team recovers the hours currently spent searching across Box, Slack, and email.</em></blockquote><h4>The Challenge</h4><p>Your organization’s documents are scattered. Box. Google Drive. Git. S3. Local shares. Getting all of that into one searchable system sounds like a major integration project — the kind that takes months and breaks often.</p><p>It doesn’t have to. The key is to connect to your existing storage without moving everything, and only to process what’s actually changed.</p><h4>How It Works: Snowflake Stages + External Connectors</h4><p>Snowflake can connect directly to your existing cloud storage — it doesn’t require you to copy everything into a new location. You point it at your S3 bucket (or Azure Blob, or GCS), and it tracks the files from there using <strong>external stages</strong>. For documents that live in Box or Google Drive, a lightweight connector (Fivetran, Airbyte, or a custom script) syncs them to S3 first:</p><pre>CREATE STAGE asset_library.raw.document_stage<br>  STORAGE_INTEGRATION = org_docs_integration<br>  URL = &#39;s3://org-asset-library/documents/&#39;<br>  DIRECTORY = (ENABLE = TRUE, AUTO_REFRESH = TRUE);</pre><p>The DIRECTORY = (ENABLE = TRUE, AUTO_REFRESH = TRUE) setting is what makes this low-maintenance — it gives you a live file listing that automatically refreshes whenever new files arrive. No manual refresh, no scheduled jobs to maintain.</p><p><strong>For Git Repositories:</strong> Code repositories need special treatment. You don’t want to index every source file — a 10,000-file monorepo isn’t a knowledge asset, it’s noise. What you want is the <em>intent</em> behind the code: the READMEs, architecture docs, and design notes.</p><p>Instead of indexing raw code, apply a <strong>summarization pipeline</strong> that extracts only what matters:</p><pre>Git Repository<br>  → Filter (README.md, docs/*, *.md, architecture/*)<br>  → AI_COMPLETE summarization<br>  → Store summary as .md<br>  → Chunk and index the summary</pre><p>This way, your asset library gains the knowledge captured in your code repositories without drowning in boilerplate utility functions.</p><h4>Keeping Up With Changes — Incremental Updates</h4><p>Here’s a practical concern: you don’t want to reprocess 10,000 documents every night just because three files changed. That’s slow, expensive, and unnecessary.</p><p><strong>The solution: track file metadata and only process what’s new or changed.</strong></p><pre>-- Directory table gives you file metadata<br>SELECT<br>  RELATIVE_PATH,<br>  SIZE,<br>  LAST_MODIFIED,<br>  MD5<br>FROM DIRECTORY(@asset_library.raw.document_stage);</pre><p>Each file in the stage has a path, a size, a last-modified timestamp, and a content hash (MD5). Compare that against a log of what you&#39;ve already processed:</p><pre>-- Find new or modified files<br>SELECT d.RELATIVE_PATH, d.LAST_MODIFIED, d.MD5<br>FROM DIRECTORY(@asset_library.raw.document_stage) d<br>LEFT JOIN asset_library.processed.document_log l<br>  ON d.RELATIVE_PATH = l.file_path<br>WHERE l.file_path IS NULL                    -- New file<br>   OR l.md5_hash != d.MD5                   -- Modified file<br>   OR l.last_modified &lt; d.LAST_MODIFIED;    -- Updated</pre><p><strong>What happens when a document is updated in Box?</strong> The connector syncs the new version to S3. Snowflake sees the updated LAST_MODIFIED timestamp. The pipeline picks it up, reprocesses it, and automatically retires the old version so stale content doesn&#39;t surface in search results:</p><pre>-- Retire old chunks when a document is reprocessed<br>UPDATE asset_library.processed.chunks<br>SET is_active = FALSE, retired_at = CURRENT_TIMESTAMP()<br>WHERE file_path = :reprocessed_file_path<br>  AND is_active = TRUE;</pre><p><strong>For duplicate detection:</strong> If the same document gets uploaded to two different folders, you don’t want two copies polluting search results. Compute a content hash after parsing — if two documents produce the same hash, retire the older one automatically.</p><pre>-- After parsing, check for content duplicates<br>SELECT content_hash, COUNT(*) as copies, <br>       MIN(ingested_at) as first_seen<br>FROM asset_library.processed.documents<br>GROUP BY content_hash<br>HAVING COUNT(*) &gt; 1;</pre><h3>Layer 2: Teaching the System to Read Your Documents</h3><blockquote><strong><em>Business impact:</em></strong><em> The difference between useful answers and useless fragments. When a consultant asks “What was the resource plan?”, they get the </em>complete<em> spreadsheet — not half a row torn out of context. This is what makes adoption stick: people trust the system because the answers actually make sense.</em></blockquote><h4>The Challenge</h4><p>Think of how you’d hand a document to a new employee. A PDF report needs to be read page by page. A PowerPoint deck makes most sense slide by slide. An Excel spreadsheet makes no sense if you tear it apart row by row — you need the whole sheet with its column headers to understand any single row.</p><p>AI systems face the same problem. Your asset library contains PDFs, PowerPoints, Markdown files, Excel spreadsheets, Word documents, and images — and each format has its own natural structure. Feed them into a generic text splitter, and you destroy the context that makes them useful.</p><h4>Parsing: Extracting Text with AI_PARSE_DOCUMENT</h4><p>Snowflake’s AI_PARSE_DOCUMENT function extracts text from PDFs, supports OCR for scanned documents, and preserves document structure including tables and headings. Think of it as a smart reader that understands document formatting, not just raw characters.</p><pre>-- Parse a PDF from stage<br>SELECT AI_PARSE_DOCUMENT(<br>    TO_FILE(&#39;@asset_library.raw.document_stage&#39;, &#39;architecture/migration-design-v2.pdf&#39;),<br>    {&#39;mode&#39;: &#39;LAYOUT&#39;, &#39;page_split&#39;: TRUE}<br>) AS parsed_content;</pre><p>The function supports two modes:</p><ul><li><strong>OCR</strong> — Pure text extraction (fast, good for scanned documents)</li><li><strong>LAYOUT</strong> — Preserves tables, headings, and structural layout (better for architecture docs with diagrams described in text)</li></ul><p>The page_split: true option gives you content broken down by page — which brings us to the critical question...</p><h4>Smart Splitting — One Size Does NOT Fit All</h4><p>This is where most AI document systems cut corners — and pay for it in search quality. They apply the same “split every 500 tokens” strategy regardless of document type. But a PowerPoint slide is not a PDF page is not an Excel sheet. Each format has natural boundaries that must be respected, or you end up with useless fragments in your search index.</p><p><strong>The right splitting strategy depends on the document type. Here’s the full breakdown:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQEp3SLcHneyWIPR9WuUcQ.png" /><figcaption>Figure 2: Document type wise chunking strategy (Image credit : Author)</figcaption></figure><p><strong>Here’s how the processing pipeline routes by file type (conceptual — each helper function like </strong><strong>parse_pdf_page_wise would be implemented as a separate UDF):</strong></p><pre>-- Route processing by document type (simplified pseudo-SQL showing routing logic)<br>CREATE OR REPLACE PROCEDURE asset_library.pipeline.process_document(<br>    file_path STRING, file_type STRING<br>)<br>RETURNS TABLE(chunk_text STRING, chunk_index INT, section_heading STRING)<br>LANGUAGE SQL<br>AS<br>$$<br>BEGIN<br>  CASE :file_type<br>    WHEN &#39;pdf&#39; THEN<br>      -- Page-wise: AI_PARSE_DOCUMENT with page_split gives us pages<br>      -- Then subdivide any page &gt; 800 tokens by paragraph breaks<br>      RETURN TABLE(<br>        SELECT page_content, page_index, page_heading<br>        FROM TABLE(parse_pdf_page_wise(:file_path))<br>      );<br>      <br>    WHEN &#39;pptx&#39; THEN<br>      -- Slide-wise: each slide = one chunk<br>      -- Slide title becomes the section_heading metadata<br>      RETURN TABLE(<br>        SELECT slide_content, slide_index, slide_title<br>        FROM TABLE(parse_ppt_slide_wise(:file_path))<br>      );<br>      <br>    WHEN &#39;docx&#39; THEN<br>      -- Heading-wise: split at H1/H2 boundaries<br>      -- Preserves the heading hierarchy as metadata<br>      RETURN TABLE(<br>        SELECT section_content, section_index, heading_text<br>        FROM TABLE(parse_doc_heading_wise(:file_path))<br>      );<br>      <br>    WHEN &#39;md&#39; THEN<br>      -- Header-wise: split at ## boundaries<br>      -- Each ## section is a semantically complete unit<br>      RETURN TABLE(<br>        SELECT section_content, section_index, header_text<br>        FROM TABLE(split_markdown_by_headers(:file_path))<br>      );<br>      <br>    WHEN &#39;xlsx&#39; THEN<br>      -- Sheet-wise: each sheet = one chunk<br>      -- Include column headers and sheet name as context<br>      RETURN TABLE(<br>        SELECT sheet_content, sheet_index, sheet_name<br>        FROM TABLE(parse_excel_sheet_wise(:file_path))<br>      );<br>      <br>    WHEN &#39;png&#39; THEN<br>      -- OCR: extract text, keep as single chunk<br>      RETURN TABLE(<br>        SELECT ocr_text, 0, &#39;Image: &#39; || :file_path<br>        FROM TABLE(ocr_and_describe(:file_path))<br>      );<br>      <br>    ELSE<br>      -- Default: treat as plain text, split by token count<br>      RETURN TABLE(<br>        SELECT chunk_text, chunk_index, &#39;&#39;<br>        FROM TABLE(split_text_by_tokens(:file_path, 600, 100))<br>      );<br>  END CASE;<br>END;<br>$$;</pre><h4>When a Single Section Is Too Large</h4><p>Some PDF pages are dense. Some Word document sections run for pages. What happens when a single natural unit is still too large for the search index to handle well?</p><p><strong>Apply a second pass of splitting with overlap — but keep the parent context:</strong></p><pre>-- For any chunk &gt; 800 tokens, subdivide with overlap<br>-- This preserves the parent section_heading metadata<br>INSERT INTO asset_library.processed.chunks<br>SELECT<br>    document_id,<br>    chunk_index,<br>    CASE <br>      WHEN LENGTH(chunk_text) / 4 &gt; 800 THEN  -- rough token estimate<br>        sub_chunk.value::STRING<br>      ELSE chunk_text<br>    END AS final_chunk_text,<br>    section_heading,<br>    file_path,<br>    CURRENT_TIMESTAMP()<br>FROM asset_library.processed.raw_chunks,<br>LATERAL FLATTEN(<br>    input =&gt; CASE <br>      WHEN LENGTH(chunk_text) / 4 &gt; 800 <br>      THEN split_with_overlap(chunk_text, 600, 100)<br>      ELSE ARRAY_CONSTRUCT(chunk_text)<br>    END<br>) sub_chunk;</pre><p>The key insight: <strong>secondary splitting always preserves the parent section’s heading as metadata</strong>. So even a sub-chunk buried in page 7 of a PDF still knows it came from the “Migration Architecture” section — making it retrievable when someone searches for that topic.</p><h4>Why the Right Splitting Strategy Directly Impacts Business Outcomes</h4><p>Here’s the difference in practice. Someone asks: “What was the resource plan for the Teradata migration?”</p><ul><li><strong>Bad splitting (arbitrary token boundaries):</strong> You get half a row from the estimation spreadsheet — Role, but no Count, no Duration, no Rate. Useless.</li><li><strong>Good splitting (sheet-wise for Excel):</strong> You get the complete “Resource Plan” sheet with all column headers intact. Immediately usable.</li></ul><p>Same for PowerPoint: split by slide, and when someone asks “What was the architecture diagram approach?”, they get the complete slide — title, bullet points, speaker notes — not a fragment that makes no sense in isolation.</p><p><strong>The chunking strategy is not a technical detail. It’s what determines whether answers are useful or garbage.</strong></p><h4>Protecting Sensitive Content — What Gets Indexed</h4><p>This step is non-negotiable. Your SOWs may contain client pricing. Your architecture docs may reference client names. Your HR documents may contain personal information. You cannot let all of that flow into a searchable index without controls.</p><p><strong>Every document is automatically classified before it’s indexed.</strong> Snowflake’s AI_CLASSIFY reads each piece of content and assigns a sensitivity level:</p><pre>-- Classify document sensitivity<br>SELECT <br>    document_id,<br>    AI_CLASSIFY(<br>        chunk_text,<br>        [&#39;public&#39;, &#39;internal&#39;, &#39;confidential&#39;, &#39;restricted&#39;]<br>    ):labels[0]::STRING AS sensitivity_level<br>FROM asset_library.processed.chunks;</pre><ul><li><strong>restricted</strong> — Excluded from the search index entirely. Never queryable, regardless of user role.</li><li><strong>confidential</strong> — Indexed but only queryable by authorized roles (see Layer 6: Governance).</li><li><strong>internal</strong> — Available to all employees.</li><li><strong>public</strong> — Available to all users.</li></ul><p>No sensitive document reaches the search index unless the system explicitly decides it should be there.</p><h4>Automatic Categorization — No Manual Tagging Required</h4><p>Beyond sensitivity, documents are automatically tagged by domain and technology — so users can filter by “cloud migration” or “Snowflake” without anyone manually labeling thousands of files:</p><pre>-- Auto-categorize documents<br>SELECT <br>    document_id,<br>    AI_CLASSIFY(<br>        chunk_text,<br>        [&#39;data-engineering&#39;, &#39;cloud-migration&#39;, &#39;analytics&#39;, <br>         &#39;machine-learning&#39;, &#39;governance&#39;, &#39;architecture&#39;]<br>    ):labels[0]::STRING AS domain,<br>    AI_CLASSIFY(<br>        chunk_text,<br>        [&#39;snowflake&#39;, &#39;databricks&#39;, &#39;teradata&#39;, &#39;oracle&#39;, <br>         &#39;aws&#39;, &#39;azure&#39;, &#39;gcp&#39;]<br>    ):labels[0]::STRING AS technology<br>FROM asset_library.processed.chunks;</pre><p>These categories become <strong>filter attributes</strong> in the search layer — meaning a user can narrow their search to “cloud migration documents about Snowflake” before they even type their question. More on that next.</p><h3>Layer 3: Search — Surfacing the Right Answer Instantly</h3><blockquote><strong><em>Business impact:</em></strong><em> Sub-second answers regardless of how large your document library grows. Users don’t need to guess the right keywords — the system understands what they mean, not just what they type. Recent and popular documents surface first, so the most battle-tested assets always appear at the top.</em></blockquote><h4>The Challenge</h4><p>You’ve processed thousands of documents. Now someone asks: “What was the automation framework we used for the Teradata migration for the banking client?” How do you reliably find the right 3–5 relevant sections out of 100,000 indexed pieces?</p><h4>How Search Works: Hybrid Retrieval with Cortex Search</h4><p>Traditional keyword search fails here. If the document says “automated DDL conversion” but the user asks about “automation framework”, a keyword search finds nothing. If you only use semantic/AI search, you lose precision on exact terms.</p><p>Cortex Search solves this by combining three techniques — <strong>vector similarity</strong> (semantic meaning), <strong>text matching</strong> (keyword precision), and <strong>reranking</strong> (relevance fine-tuning) — all running as a fully managed, serverless service. You configure it; Snowflake handles the infrastructure.</p><pre>CREATE CORTEX SEARCH SERVICE asset_library.search.document_search<br>  ON chunk_text<br>  ATTRIBUTES domain, technology, sensitivity_level, document_type<br>  WAREHOUSE = asset_lib_wh<br>  TARGET_LAG = &#39;1 hours&#39;<br>  AS (<br>    SELECT <br>        chunk_text,<br>        section_heading,<br>        file_path,<br>        document_title,<br>        domain,<br>        technology,<br>        sensitivity_level,<br>        document_type,<br>        created_at,<br>        view_count<br>    FROM asset_library.processed.enriched_chunks<br>    WHERE sensitivity_level != &#39;restricted&#39;<br>  );</pre><p><strong>Key elements:</strong></p><ul><li>ON chunk_text — This is what gets semantically indexed</li><li>ATTRIBUTES — These become filterable dimensions (domain, technology, sensitivity)</li><li>TARGET_LAG = &#39;1 hours&#39; — New documents become searchable within an hour</li><li>The WHERE clause excludes restricted content at the index level — it never enters the search service</li></ul><h4>Surfacing the Best Results: Recency and Popularity Signals</h4><p>Not all documents are equally useful. A migration guide from last month is more relevant than one from three years ago. A document viewed 50 times by your team has been validated by crowd wisdom.</p><p>Two built-in scoring signals let you encode this logic: <strong>time decay</strong> (recent documents rank higher) and <strong>numeric boost</strong> (popular documents rank higher). Think of it like a search engine that knows your documents’ history.</p><pre>{<br>  &quot;query&quot;: &quot;teradata migration automation framework&quot;,<br>  &quot;columns&quot;: [&quot;chunk_text&quot;, &quot;document_title&quot;, &quot;file_path&quot;, &quot;section_heading&quot;],<br>  &quot;filter&quot;: {<br>    &quot;@and&quot;: [<br>      {&quot;@eq&quot;: {&quot;technology&quot;: &quot;teradata&quot;}},<br>      {&quot;@eq&quot;: {&quot;domain&quot;: &quot;cloud-migration&quot;}}<br>    ]<br>  },<br>  &quot;scoring_config&quot;: {<br>    &quot;functions&quot;: {<br>      &quot;time_decays&quot;: [<br>        {<br>          &quot;column&quot;: &quot;created_at&quot;,<br>          &quot;weight&quot;: 2,<br>          &quot;limit_hours&quot;: 8760<br>        }<br>      ],<br>      &quot;numeric_boosts&quot;: [<br>        {<br>          &quot;column&quot;: &quot;view_count&quot;,<br>          &quot;weight&quot;: 1<br>        }<br>      ]<br>    }<br>  },<br>  &quot;limit&quot;: 10<br>}</pre><p><strong>What this does:</strong></p><ul><li>time_decays on created_at with limit_hours: 8760 (365 days) — documents older than a year get progressively less boost, but aren&#39;t excluded. Recent docs surface first.</li><li>numeric_boosts on view_count — surfaces popular documents. This is the crowd-wisdom signal: if 50 people found a document useful, it&#39;s probably good.</li><li>The filter narrows results to Teradata + cloud-migration domain <em>before</em> ranking — reducing noise significantly.</li><li>weight values are relative. Setting time_decay weight to 2 and numeric_boost weight to 1 means recency matters twice as much as popularity.</li></ul><h4>Reusable Scoring Profiles — Set It Once, Apply Everywhere</h4><p>Instead of repeating the same scoring logic in every query, save it as a named profile on the search service:</p><pre>ALTER CORTEX SEARCH SERVICE asset_library.search.document_search<br>  ADD SCORING PROFILE recent_and_popular<br>  &#39;{<br>    &quot;functions&quot;: {<br>      &quot;time_decays&quot;: [<br>        {&quot;column&quot;: &quot;created_at&quot;, &quot;weight&quot;: 2, &quot;limit_hours&quot;: 8760}<br>      ],<br>      &quot;numeric_boosts&quot;: [<br>        {&quot;column&quot;: &quot;view_count&quot;, &quot;weight&quot;: 1}<br>      ]<br>    }<br>  }&#39;;</pre><p>Then reference it in queries (via the REST API or Python SDK):</p><pre># Python SDK — query with a named scoring profile<br>from snowflake.core import Root<br>root = Root(session)<br>search_service = root.databases[&quot;ASSET_LIBRARY&quot;].schemas[&quot;SEARCH&quot;].cortex_search_services[&quot;DOCUMENT_SEARCH&quot;]<br>results = search_service.search(<br>    query=&quot;teradata migration automation&quot;,<br>    columns=[&quot;chunk_text&quot;, &quot;document_title&quot;, &quot;file_path&quot;, &quot;section_heading&quot;],<br>    scoring_profile=&quot;recent_and_popular&quot;,<br>    limit=10<br>)</pre><p>One profile to maintain. Every query automatically benefits from it.</p><h4>From Search Results to Direct Downloads — Full Traceability</h4><p>Search results alone aren’t enough. Users need to trust the answer — and the only way to build that trust is to let them click through and read the original document for themselves.</p><p>Every search result needs: a synthesized answer, the source citation, <strong>and a one-click download link</strong> to the original file.</p><p>The mechanism is Snowflake’s GET_PRESIGNED_URL — it generates a short-lived, secure download link for any file on a stage. The key design decision: <strong>store the </strong><strong>file_path in every indexed chunk</strong>, then generate a fresh URL at query time.</p><pre>-- After Cortex Search returns results, generate download links<br>-- This runs in the application layer (Streamlit or Agent post-processing)<br>SELECT <br>    chunk_text,<br>    document_title,<br>    section_heading,<br>    file_path,<br>    GET_PRESIGNED_URL(<br>        @asset_library.raw.document_stage, <br>        file_path, <br>        3600  -- URL valid for 1 hour<br>    ) AS download_url<br>FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));</pre><p><strong>Why not pre-generate and store these URLs in the index?</strong> Because they expire. A URL generated at indexing time would be dead by the time someone queries it — sometimes hours or days later. Generate fresh URLs on every search instead — they cost almost nothing to create and are guaranteed to work.</p><p><strong>Wrap this pattern in a view for a clean, reusable interface:</strong></p><pre>-- View that enriches search results with download links<br>CREATE OR REPLACE VIEW asset_library.app.searchable_docs AS<br>SELECT <br>    chunk_text,<br>    document_title,<br>    section_heading,<br>    file_path,<br>    domain,<br>    technology,<br>    sensitivity_level,<br>    document_type,<br>    created_at,<br>    view_count,<br>    GET_PRESIGNED_URL(<br>        @asset_library.raw.document_stage, <br>        file_path, <br>        600<br>    ) AS presigned_download_url<br>FROM asset_library.processed.enriched_chunks<br>WHERE sensitivity_level != &#39;restricted&#39;;</pre><p>When results come back from search, the application generates a fresh download link for each cited document. The user gets: a plain-language answer, source citation, and a one-click download. Full traceability — they can verify everything themselves.</p><p>This is where the Cortex Agent comes in to tie it all together.</p><h3>Layer 4: The AI Assistant — Ask a Question, Get an Answer</h3><blockquote><strong><em>Business impact:</em></strong><em> Zero learning curve. New hires can ask questions on day one and get the same quality answers as a 10-year veteran. No training, no query syntax, no keyword guessing. The system handles follow-up questions naturally, so finding information feels like asking a knowledgeable colleague — not wrestling with a search engine.</em></blockquote><h4>Your Organization’s Expert on Call</h4><p>Think of the Cortex Agent as a knowledgeable colleague who has read every document in your organization — and can instantly recall the right one when you ask. Users type a question in plain English. The agent figures out what to search for, reads the most relevant pieces, and writes a clear answer — with citations and download links to the source documents.</p><p>Under the hood, a Cortex Agent connects the search service to a large language model. When a user asks a question, the agent decides what to search for, retrieves the relevant chunks, synthesizes an answer, and cites its sources. The entire conversation is stateful — follow-up questions work naturally.</p><pre>CREATE OR REPLACE AGENT asset_library.app.doc_agent<br>  COMMENT = &#39;Organization Asset Library assistant&#39;<br>  FROM SPECIFICATION<br>$$<br>tools:<br>  - tool_spec:<br>      type: cortex_search<br>      name: asset_search<br>tool_resources:<br>  asset_search:<br>    name: &quot;ASSET_LIBRARY.SEARCH.DOCUMENT_SEARCH&quot;<br>    max_results: 5<br>    title_column: &quot;document_title&quot;<br>    id_column: &quot;file_path&quot;<br>instructions:<br>  response: |<br>    You are the Organization Asset Library assistant. When users ask questions,<br>    search the document library and provide answers with source citations.<br>    Always include the file path so users can access the original document.<br>    If you cannot find a relevant source, say so clearly - never fabricate information.<br>$$;</pre><p><strong>Why this delivers real business value:</strong></p><ul><li>The agent decides <em>when</em> to search and <em>what</em> to search for — users don’t need to know the right keywords</li><li>It reformulates vague questions into precise searches, catching intent even when terminology differs</li><li>Every answer cites the exact source document — users can download and verify rather than just trust the AI</li><li>Follow-up questions work naturally, so a conversation feels like consulting a colleague, not running a search query</li></ul><h4>What a Real Interaction Looks Like</h4><p>Here’s a typical exchange — no training, no keyword guessing, just a plain question:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QgvfGrmm6K82fqxY_a78FA.png" /><figcaption>Figure 3: Agent response to user Question (Sample)(Image credit : Author)</figcaption></figure><p>Three things to notice:</p><ol><li><strong>Citations include page numbers, sections, and sheet names</strong> — this is only possible because the type-aware chunking in Layer 2 preserved that metadata</li><li><strong>Each result has a direct download link</strong> — a secure URL generated on-the-fly via GET_PRESIGNED_URLvalid for 1 hour</li><li><strong>Full traceability</strong> — users aren’t just trusting the AI. They can click, download, and verify the original document for themselves. That’s what builds trust in the system.</li></ol><h3>Layer 5: The User Interface — What Your Team Actually Uses</h3><blockquote><strong><em>Business impact:</em></strong><em> Adoption requires zero training. Open a browser, type a question, get an answer with a download link to the original file. No new tools to learn, no special syntax, no IT ticket required. If someone can use Google, they can use this.</em></blockquote><h4>Designing for People, Not Engineers</h4><p>Your users shouldn’t need to know what Cortex Search is, or what a vector embedding looks like. They should open a web page, type a question, and get an answer.</p><p>The interface is built with Streamlit in Snowflake — a Python-based web framework that runs natively inside Snowflake. No external hosting, no separate deployment pipeline. It lives in the same Snowflake account as all the data.</p><pre>import streamlit as st<br>import json<br>from snowflake.snowpark.context import get_active_session<br>session = get_active_session()<br>st.title(&quot;Organization Asset Library&quot;)<br>st.caption(&quot;Ask questions about our projects, architectures, and documentation&quot;)<br># Sidebar filters for power users<br>with st.sidebar:<br>    st.header(&quot;Filters&quot;)<br>    domain = st.multiselect(&quot;Domain&quot;, <br>        [&quot;data-engineering&quot;, &quot;cloud-migration&quot;, &quot;analytics&quot;, <br>         &quot;machine-learning&quot;, &quot;governance&quot;, &quot;architecture&quot;])<br>    technology = st.multiselect(&quot;Technology&quot;,<br>        [&quot;snowflake&quot;, &quot;teradata&quot;, &quot;databricks&quot;, &quot;aws&quot;, &quot;azure&quot;, &quot;gcp&quot;])<br>    doc_type = st.multiselect(&quot;Document Type&quot;,<br>        [&quot;pdf&quot;, &quot;pptx&quot;, &quot;docx&quot;, &quot;md&quot;, &quot;xlsx&quot;])<br>    date_after = st.date_input(&quot;Modified after&quot;, value=None)<br># Chat interface<br>query = st.chat_input(&quot;What are you looking for?&quot;)<br>if query:<br>    with st.chat_message(&quot;user&quot;):<br>        st.write(query)<br>    <br>    with st.chat_message(&quot;assistant&quot;):<br>        # Call Cortex Agent via DATA_AGENT_RUN<br>        # Note: Requires container runtime for Streamlit in Snowflake<br>        request_body = json.dumps({<br>            &quot;messages&quot;: [<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: [{&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: query}]}<br>            ]<br>        })<br>        <br>        result = session.sql(f&quot;&quot;&quot;<br>            SELECT TRY_PARSE_JSON(<br>                SNOWFLAKE.CORTEX.DATA_AGENT_RUN(<br>                    &#39;ASSET_LIBRARY.APP.DOC_AGENT&#39;,<br>                    $${request_body}$$,<br>                    TRUE<br>                )<br>            ) AS resp<br>        &quot;&quot;&quot;).collect()[0][&quot;RESP&quot;]<br>        <br>        response = json.loads(result)<br>        <br>        # Extract text and citations from agent response<br>        for content_block in response.get(&quot;content&quot;, []):<br>            if content_block.get(&quot;type&quot;) == &quot;text&quot;:<br>                st.markdown(content_block[&quot;text&quot;])<br>            elif content_block.get(&quot;type&quot;) == &quot;tool_results&quot;:<br>                # Show sources with pre-signed download links<br>                citations = content_block.get(&quot;citations&quot;, [])<br>                if citations:<br>                    st.divider()<br>                    st.subheader(&quot;Sources&quot;)<br>                    for source in citations:<br>                        file_path = source.get(&quot;id&quot;, &quot;&quot;)<br>                        title = source.get(&quot;title&quot;, file_path)<br>                        # Generate a fresh pre-signed URL (valid 1 hour)<br>                        presigned_url = session.sql(f&quot;&quot;&quot;<br>                            SELECT GET_PRESIGNED_URL(<br>                                @asset_library.raw.document_stage, <br>                                &#39;{file_path}&#39;, <br>                                3600<br>                            )<br>                        &quot;&quot;&quot;).collect()[0][0]<br>                        <br>                        col1, col2 = st.columns([4, 1])<br>                        with col1:<br>                            st.markdown(f&quot;**{title}**&quot;)<br>                            st.caption(file_path)<br>                        with col2:<br>                            st.link_button(&quot;Download&quot;, presigned_url)<br>        <br>        # Feedback buttons<br>        st.divider()<br>        col1, col2 = st.columns(2)<br>        with col1:<br>            if st.button(&quot;Helpful&quot;, key=f&quot;up_{query}&quot;):<br>                log_feedback(query, score=5)<br>                st.success(&quot;Thanks for the feedback!&quot;)<br>        with col2:<br>            if st.button(&quot;Not helpful&quot;, key=f&quot;down_{query}&quot;):<br>                log_feedback(query, score=1)<br>                st.info(&quot;Sorry about that. We&#39;ll use this to improve.&quot;)</pre><blockquote><strong><em>Note:</em></strong><em> Cortex Agents APIs require a </em><strong><em>container runtime</em></strong><em> when called from Streamlit in Snowflake. Set your SiS app to use a container runtime rather than a warehouse runtime.</em></blockquote><p><strong>Every design decision here was made to serve the user, not the engineer:</strong></p><ul><li><strong>Answer first</strong> — Users want answers, not a list of links to read themselves</li><li><strong>Sources below with one-click downloads</strong> — GET_PRESIGNED_URL Generates a time-limited link for the original file on stage. The browser downloads directly from cloud storage — no file bytes passing through the app.</li><li><strong>st.link_button instead of </strong><strong>st.download_button</strong> — Pre-signed URLs are direct cloud storage links. The browser handles the download natively, which is faster for large PDFs and avoids loading bytes of the file into the app&#39;s memory.</li><li><strong>Sidebar filters</strong> — Power users can narrow by domain, technology, or document type before asking — reducing noise on broad queries</li><li><strong>Inline feedback</strong> — Captures quality signals in the moment, without interrupting the user’s flow</li></ul><h3>Layer 6: Security &amp; Governance — Who Sees What</h3><blockquote><strong><em>Business impact:</em></strong><em> You can make sensitive documents searchable </em>without<em> making them accessible to everyone. Client pricing, internal HR documents, and executive materials stay visible only to authorized roles — enforced by the platform itself, not by trust in application code. This is what lets legal and compliance say “yes” to the project.</em></blockquote><h4>The Challenge</h4><p>This is the question that should make any compliance or legal stakeholder pause: if you make all your organization’s documents searchable, what stops the wrong person from seeing the wrong document?</p><p>Most quick AI document solutions never answer this question. They index everything and hope for the best. A production-grade system needs hard access controls — enforced at the data layer, not just the UI.</p><p>Snowflake’s role-based access control (RBAC) integrates directly with Cortex Search, so the access rules you already use for your data apply automatically to document search results.</p><h4>Role-Based Access Control (RBAC) on Search Results</h4><p>There are two approaches to enforcing access tiers — choose based on your security requirements:</p><p><strong>Approach 1: Separate search services per security tier</strong> <em>(stronger isolation)</em></p><p>Each tier is a completely separate search service. Even if an application bug bypasses a filter, a user in a lower-privileged role physically cannot access a higher-tier search service.</p><blockquote><strong><em>Cost trade-off:</em></strong><em> Because each service is a cumulative superset, a </em><em>public document is vectorized and stored in all three services, an </em><em>internal document in two. In the worst case, public content pays 3x on embedding storage and each service runs its own </em><em>TARGET_LAG refresh pipeline independently. This duplication is the explicit price of Snowflake-native enforcement — acceptable for regulated environments, but worth factoring in for large corpora.</em></blockquote><pre>-- Public knowledge base — everyone can access<br>CREATE CORTEX SEARCH SERVICE asset_library.search.public_docs<br>  ON chunk_text<br>  ATTRIBUTES domain, technology, document_type<br>  WAREHOUSE = asset_lib_wh<br>  TARGET_LAG = &#39;1 hours&#39;<br>  AS (<br>    SELECT * FROM enriched_chunks <br>    WHERE sensitivity_level = &#39;public&#39;<br>  );<br>-- Internal knowledge base - employees only<br>CREATE CORTEX SEARCH SERVICE asset_library.search.internal_docs<br>  ON chunk_text<br>  ATTRIBUTES domain, technology, document_type<br>  WAREHOUSE = asset_lib_wh<br>  TARGET_LAG = &#39;1 hours&#39;<br>  AS (<br>    SELECT * FROM enriched_chunks <br>    WHERE sensitivity_level IN (&#39;public&#39;, &#39;internal&#39;)<br>  );<br>-- Confidential - restricted roles only<br>CREATE CORTEX SEARCH SERVICE asset_library.search.confidential_docs<br>  ON chunk_text<br>  ATTRIBUTES domain, technology, document_type<br>  WAREHOUSE = asset_lib_wh<br>  TARGET_LAG = &#39;1 hours&#39;<br>  AS (<br>    SELECT * FROM enriched_chunks <br>    WHERE sensitivity_level IN (&#39;public&#39;, &#39;internal&#39;, &#39;confidential&#39;)<br>  );</pre><p>Grant access at the Snowflake role level — the same way you’d grant access to a table or database:</p><pre>GRANT USAGE ON CORTEX SEARCH SERVICE asset_library.search.confidential_docs<br>  TO ROLE senior_executives;<br>GRANT USAGE ON CORTEX SEARCH SERVICE asset_library.search.internal_docs<br>  TO ROLE all_employees;</pre><p>The application resolves which service to call by checking the user’s current role and mapping it to the highest-access service they are granted. Because each service is a cumulative superset, a single call to the highest service is sufficient — there is no need to merge results from multiple services.</p><pre># Route user to the highest-access service they are granted<br>role_to_service = {<br>    &#39;PUBLIC_ROLE&#39;:       &#39;asset_library.search.public_docs&#39;,<br>    &#39;ALL_EMPLOYEES&#39;:     &#39;asset_library.search.internal_docs&#39;,<br>    &#39;SENIOR_EXECUTIVES&#39;: &#39;asset_library.search.confidential_docs&#39;,<br>}<br>service_name = role_to_service.get(session.get_current_role(), &#39;public_docs&#39;)<br># The GRANT is the enforcement backstop - if the map routes incorrectly,<br># Snowflake will deny the call before any data is returned<br>results = session.cortex.search(<br>    service=service_name,<br>    query=user_query,<br>    limit=10<br>)</pre><p>If a user’s role is not in the map, they fall back to the public service — an explicit safe default.</p><p><strong>Approach 2: Single service with application-layer role enforcement</strong> <em>(simpler to manage, weaker server-side guarantee)</em></p><p>If you prefer one search service for all tiers, restrict results in the application based on the user’s current Snowflake role:</p><pre># In your Streamlit app — enforce access based on current role<br>user_role = session.get_current_role()<br># Map roles to allowed sensitivity levels<br>role_access = {<br>    &#39;PUBLIC&#39;: [&#39;public&#39;],<br>    &#39;ALL_EMPLOYEES&#39;: [&#39;public&#39;, &#39;internal&#39;],<br>    &#39;SENIOR_EXECUTIVES&#39;: [&#39;public&#39;, &#39;internal&#39;, &#39;confidential&#39;]<br>}<br>allowed_levels = role_access.get(user_role, [&#39;public&#39;])<br># Apply filter to every search query<br>results = search_service.search(<br>    query=user_query,<br>    filter={&quot;@contains&quot;: {&quot;sensitivity_level&quot;: allowed_levels}},<br>    limit=10<br>)</pre><blockquote><em>⚠️ </em><strong><em>Bypass risk:</em></strong><em> The sensitivity filter above is enforced by your application, not by Snowflake. Any user who holds </em><em>USAGE on this search service — via the REST API, Python SDK, or SnowSQL — can query it without the filter and will receive documents across all sensitivity levels. This approach is only safe when direct Snowflake access is fully blocked for all end users via network policy, and no direct grants to the search service exist outside the application service account.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJi-NsSuKxCu5R0jr92b2A.png" /><figcaption>Figure 4: Cortex Search Approaches and tradeoffs (Image credit : Author)</figcaption></figure><h4>Five-Layer Document Boundary Enforcement</h4><p>For multi-client or multi-division environments, documents must never cross organizational boundaries — a document from Client A must never be visible to users working on Client B. This is enforced at five independent layers:</p><ol><li><strong>Ingestion</strong> — Only sync documents from approved sources (integration controls prevent unauthorized sources)</li><li><strong>Classification</strong> — Every document is tagged with org_unit at parse time, not at query time</li><li><strong>Search</strong> — Every query automatically filters by org_unit — no query can return results outside the user&#39;s boundary</li><li><strong>Network</strong> — Snowflake network policies restrict which IP ranges and accounts can even reach the service</li><li><strong>Audit</strong> — Every search and download is logged for compliance review — full accountability trail</li></ol><h3>Layer 7: Scales With You — From Pilot to Enterprise</h3><blockquote><strong><em>Business impact:</em></strong><em> Start with 100 documents as a proof of concept. Scale to 10,000+ without re-architecture or downtime. The system never slows down as it grows, and new documents become discoverable within minutes of upload. No “big bang” migration required — grow at your own pace, and prove value before you invest further.</em></blockquote><h4>Will This Actually Scale?</h4><p>A common concern: “This sounds great for 100 documents, but what about 10,000?” Here’s what you can concretely expect at each stage of rollout — <strong>query response stays under 1 second at every scale</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfeUx4UHR1jtBzP7pD-72w.png" /><figcaption>Figure 5: Scale (Image credit : Author)</figcaption></figure><p>The one-time initial processing time grows with document count — but that’s a fixed setup cost, not an ongoing operational burden.</p><h4>Why Search Speed Never Degrades</h4><p>Cortex Search is a fully managed service — Snowflake handles the vector indexing, text indexing, and retrieval infrastructure. You don’t tune indexes or manage infrastructure as your document library grows. Whether you have 1,000 chunks or 100,000:</p><ul><li><strong>Vector index</strong> uses ANN (Approximate Nearest Neighbor) — scales logarithmically, not linearly</li><li><strong>Text index</strong> is inverted — keyword lookup is constant time regardless of corpus size</li><li><strong>Reranking</strong> only applies to the top-k candidates (top 100 before reranking to the final 10)</li><li><strong>Filters</strong> are applied before ranking — narrowing by domain or technology means the system only scores what’s relevant</li></ul><h4>New Documents Are Searchable Within Minutes</h4><p>For near real-time ingestion, the pipeline is driven by a <strong>stream-triggered Snowflake Task</strong> — it wakes up only when new files arrive:</p><pre>-- Create a stream on the directory table to capture new files<br>CREATE STREAM asset_library.raw.new_files_stream<br>  ON STAGE asset_library.raw.document_stage;<br>-- Task runs every 5 minutes, but only when new files arrive<br>CREATE TASK asset_library.pipeline.process_new_documents<br>  WAREHOUSE = asset_lib_wh<br>  SCHEDULE = &#39;5 MINUTE&#39;<br>  WHEN SYSTEM$STREAM_HAS_DATA(&#39;asset_library.raw.new_files_stream&#39;)<br>AS<br>  CALL asset_library.pipeline.process_incremental_documents();</pre><p>The stored procedure:</p><ol><li>Reads from the stream (only new/modified files)</li><li>Routes by file type to the appropriate parsing strategy</li><li>Chunks according to document-type-specific rules</li><li>Classifies sensitivity and domain with AI_CLASSIFY</li><li>Checks for duplicates via content hash</li><li>Inserts into the enriched_chunks table</li><li>Cortex Search picks up changes within TARGET_LAG</li></ol><p><strong>Total pipeline latency: A file arrives and is searchable within 5–10 minutes.</strong></p><p>For most knowledge management use cases, this means the library is always up-to-date. A proposal uploaded this morning is discoverable before lunch. If you need near-instant availability, reduce TARGET_LAG to &#39;10 minutes&#39; and the task schedule to &#39;1 MINUTE&#39;.</p><h3>Layer 8: Monitoring &amp; Cost — Staying in Control</h3><blockquote><strong><em>Business impact:</em></strong><em> Full visibility into what the system costs and what value it delivers. Know exactly which teams use it most, which topics have coverage gaps, and whether the investment is paying off — in language your CFO will understand. No surprise bills, no hidden usage.</em></blockquote><h4>What Users Are Actually Asking</h4><p>Every search query is a signal. Tracking them tells you what your organization is looking for — and, just as importantly, what it can’t find:</p><pre>CREATE TABLE asset_library.monitoring.query_log (<br>    query_id STRING DEFAULT UUID_STRING(),<br>    user_name STRING DEFAULT CURRENT_USER(),<br>    user_role STRING DEFAULT CURRENT_ROLE(),<br>    query_text STRING,<br>    filters_applied VARIANT,<br>    results_returned INT,<br>    response_time_ms INT,<br>    feedback_score INT,<br>    feedback_text STRING,<br>    created_at TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()<br>);</pre><p><strong>Why this data matters:</strong></p><ul><li>Queries with <strong>zero results</strong> → Gaps in your document coverage. What are people looking for that you don’t have?</li><li><strong>Repeated queries</strong> on the same topic → Opportunity for a curated FAQ or featured document</li><li><strong>Low feedback scores</strong> → Quality issues to investigate. Bad chunking? Wrong classification? Stale documents?</li></ul><h4>Document Processing Health</h4><p>Knowing that the pipeline ran is not enough. You need to know it ran <em>correctly</em> — which files succeeded, which failed, and why:</p><pre>CREATE TABLE asset_library.monitoring.pipeline_log (<br>    run_id STRING DEFAULT UUID_STRING(),<br>    file_path STRING,<br>    file_type STRING,<br>    file_size_bytes INT,<br>    parse_status STRING,       -- &#39;success&#39;, &#39;failed&#39;, &#39;skipped&#39;, &#39;duplicate&#39;<br>    chunks_created INT,<br>    sensitivity_level STRING,<br>    processing_time_ms INT,<br>    error_message STRING,<br>    created_at TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP()<br>);</pre><p>Use this data to build a monitoring dashboard showing:</p><ul><li>Documents processed per day (trend)</li><li>Failure rate by file type (which formats cause problems?)</li><li>Average processing time per document type</li><li>Queue depth (files awaiting processing)</li><li>Duplicate detection rate</li></ul><h4>Understanding Your AI Costs — Two Separate Buckets</h4><p>Before looking at cost queries, it helps to understand the billing model. This system has two distinct cost centers that move independently:</p><ol><li><strong>Document Processing Pipeline Cost</strong> — What you spend parsing, classifying, and chunking documents. This cost is periodic — it spikes when you ingest a batch of new files, then drops to near-zero until the next batch.</li><li><strong>Document Search Usage Cost</strong> — What you spend when users query the library. This cost scales directly with user adoption — more users asking more questions means higher AI token usage.</li></ol><p>Understanding both buckets separately helps you budget accurately, explain costs to stakeholders, and spot anomalies.</p><h4>Cost Center 1: Document Processing Pipeline</h4><p>Every time your pipeline processes documents, it calls AI_PARSE_DOCUMENT and AI_CLASSIFY. These are Cortex AI functions billed per token. Snowflake provides a dedicated view for this — making it straightforward to see exactly what you&#39;re spending on document ingestion:</p><pre>-- Document processing cost (AI_PARSE_DOCUMENT, AI_EXTRACT, Document AI)<br>-- Use CORTEX_DOCUMENT_PROCESSING_USAGE_HISTORY (canonical view)<br>SELECT <br>    start_time::DATE AS usage_date,<br>    function_name,<br>    SUM(document_count) AS total_documents,<br>    SUM(page_count) AS total_pages,<br>    SUM(credits_used) AS total_credits<br>FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_DOCUMENT_PROCESSING_USAGE_HISTORY<br>WHERE start_time &gt; DATEADD(day, -30, CURRENT_TIMESTAMP())<br>GROUP BY 1, 2<br>ORDER BY usage_date DESC, total_credits DESC;</pre><p>For AI_CLASSIFY and other Cortex SQL functions (AI_COMPLETE for summarization, etc.), use the per-query view:</p><pre>-- Per-query AI function cost (AI_CLASSIFY, AI_COMPLETE, etc.)<br>-- CORTEX_AISQL_USAGE_HISTORY is the canonical view for per-query LLM tracking<br>SELECT <br>    usage_time::DATE AS usage_date,<br>    model_name,<br>    function_name,<br>    COUNT(*) AS query_count,<br>    SUM(tokens) AS total_tokens,<br>    SUM(token_credits) AS total_token_credits<br>FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_AISQL_USAGE_HISTORY<br>WHERE usage_time &gt; DATEADD(day, -30, CURRENT_TIMESTAMP())<br>  AND query_tag = &#39;ASSET_LIBRARY_PIPELINE&#39;  -- tag your pipeline queries!<br>GROUP BY 1, 2, 3<br>ORDER BY usage_date DESC, total_token_credits DESC;</pre><p><strong>Pro tip:</strong> Tag your pipeline queries with ALTER SESSION SET QUERY_TAG = &#39;ASSET_LIBRARY_PIPELINE&#39; before processing. This lets you isolate pipeline costs from everything else in your account.</p><p><strong>Total pipeline cost per day:</strong></p><pre>-- Combined pipeline cost: document parsing + AI classification<br>WITH doc_processing AS (<br>    SELECT <br>        start_time::DATE AS usage_date,<br>        SUM(credits_used) AS doc_parse_credits<br>    FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_DOCUMENT_PROCESSING_USAGE_HISTORY<br>    WHERE start_time &gt; DATEADD(day, -30, CURRENT_TIMESTAMP())<br>    GROUP BY 1<br>),<br>ai_classification AS (<br>    SELECT <br>        usage_time::DATE AS usage_date,<br>        SUM(token_credits) AS ai_credits<br>    FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_AISQL_USAGE_HISTORY<br>    WHERE query_tag = &#39;ASSET_LIBRARY_PIPELINE&#39;<br>      AND usage_time &gt; DATEADD(day, -30, CURRENT_TIMESTAMP())<br>    GROUP BY 1<br>)<br>SELECT <br>    COALESCE(d.usage_date, a.usage_date) AS usage_date,<br>    COALESCE(d.doc_parse_credits, 0) AS parsing_credits,<br>    COALESCE(a.ai_credits, 0) AS classification_credits,<br>    COALESCE(d.doc_parse_credits, 0) + COALESCE(a.ai_credits, 0) AS total_pipeline_credits<br>FROM doc_processing d<br>FULL OUTER JOIN ai_classification a ON d.usage_date = a.usage_date<br>ORDER BY usage_date DESC;</pre><h4>Cost Center 2: Document Search Usage</h4><p>When users search the asset library, cost comes from two places:</p><ul><li><strong>Cortex Search serving</strong> — The managed search index (always-on indexing + per-query serving cost)</li><li><strong>Cortex Agent</strong> — The LLM that reads search results and synthesizes the answer (billed per token, per query)</li></ul><p><strong>Cortex Search serving cost:</strong></p><pre>-- Cortex Search serving cost (indexing + query serving)<br>-- CORTEX_SEARCH_SERVING_USAGE_HISTORY is the canonical view<br>SELECT <br>    start_time::DATE AS usage_date,<br>    service_name,<br>    SUM(credits) AS search_serving_credits<br>FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_SEARCH_SERVING_USAGE_HISTORY<br>WHERE start_time &gt; DATEADD(day, -30, CURRENT_TIMESTAMP())<br>  AND service_name = &#39;DOCUMENT_SEARCH&#39;<br>      and DATABASE_NAME  = &#39;asset_library&#39;<br>      AND SCHEMA_NAME = &#39;search&#39;  -- your service name<br>GROUP BY 1, 2<br>ORDER BY usage_date DESC;</pre><p><strong>Cortex Agent cost (answer synthesis):</strong></p><pre>-- Cortex Agent usage (natural language answers over search results)<br>-- CORTEX_AGENT_USAGE_HISTORY tracks per-request agent billing<br>SELECT <br>    start_time::DATE AS usage_date,<br>    agent_name,<br>    COUNT(*) AS total_requests,<br>    SUM(tokens) AS total_tokens,<br>    SUM(token_credits) AS total_agent_credits<br>FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_AGENT_USAGE_HISTORY<br>WHERE start_time &gt; DATEADD(day, -30, CURRENT_TIMESTAMP())<br>  AND agent_name = &#39;DOC_AGENT&#39;  -- your agent name<br>GROUP BY 1, 2<br>ORDER BY usage_date DESC;</pre><h4>Combined Cost Dashboard: Pipeline vs. Search</h4><p>Bring both cost centers together for a single daily view:</p><pre>-- Daily cost breakdown: Pipeline vs. Search<br>WITH pipeline_cost AS (<br>    SELECT <br>        start_time::DATE AS usage_date,<br>        &#39;PIPELINE&#39; AS cost_center,<br>        SUM(credits_used) AS credits<br>    FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_DOCUMENT_PROCESSING_USAGE_HISTORY<br>    WHERE start_time &gt; DATEADD(day, -30, CURRENT_TIMESTAMP())<br>    GROUP BY 1<br>),<br>pipeline_ai_cost AS (<br>    SELECT <br>        usage_time::DATE AS usage_date,<br>        &#39;PIPELINE&#39; AS cost_center,<br>        SUM(token_credits) AS credits<br>    FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_AISQL_USAGE_HISTORY<br>    WHERE usage_time &gt; DATEADD(day, -30, CURRENT_TIMESTAMP())<br>      AND query_tag = &#39;ASSET_LIBRARY_PIPELINE&#39;<br>    GROUP BY 1<br>),<br>search_cost AS (<br>    SELECT <br>        start_time::DATE AS usage_date,<br>        &#39;SEARCH_SERVING&#39; AS cost_center,<br>        SUM(credits) AS credits<br>    FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_SEARCH_SERVING_USAGE_HISTORY<br>    WHERE start_time &gt; DATEADD(day, -30, CURRENT_TIMESTAMP())<br>      AND service_name = &#39;DOCUMENT_SEARCH&#39;<br>      and DATABASE_NAME  = &#39;asset_library&#39;<br>      AND SCHEMA_NAME = &#39;search&#39;<br>    GROUP BY 1<br>),<br>agent_cost AS (<br>    SELECT <br>        start_time::DATE AS usage_date,<br>        &#39;AGENT&#39; AS cost_center,<br>        SUM(token_credits) AS credits<br>    FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_AGENT_USAGE_HISTORY<br>    WHERE start_time &gt; DATEADD(day, -30, CURRENT_TIMESTAMP())<br>      AND agent_name = &#39;DOC_AGENT&#39;<br>    GROUP BY 1<br>)<br>SELECT * FROM pipeline_cost<br>UNION ALL SELECT * FROM pipeline_ai_cost<br>UNION ALL SELECT * FROM search_cost<br>UNION ALL SELECT * FROM agent_cost<br>ORDER BY usage_date DESC, cost_center;</pre><p>This gives your finance team a single daily view of every dollar spent — broken down by what caused it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSIWBL0lhirpnKFNk6_0Cw.png" /><figcaption>Figure 6: Service wise credit usage (Sample)(Image credit : Author)</figcaption></figure><p><strong>What this tells you — and your stakeholders:</strong></p><ul><li><strong>Pipeline cost</strong> spikes on days you ingest new documents. Zero on days you don’t — it’s a batch cost, not an ongoing one.</li><li><strong>Search serving</strong> is relatively flat — it’s always-on indexing plus a small per-query component.</li><li><strong>Agent cost</strong> scales directly with user adoption. On July 21st, the pipeline was idle but 4.21 credits went to users getting answers. That’s cost you want to see grow.</li></ul><h4>Reconciling Against Snowflake’s Top-Level Billing</h4><p>To confirm your asset library’s total AI spend matches what Snowflake is billing you, cross-check against the top-level metering view:</p><pre>-- Validate total AI spend from this application<br>SELECT <br>    service_type,<br>    start_time::DATE AS usage_date,<br>    SUM(credits_used) AS total_credits<br>FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_HISTORY<br>WHERE service_type IN (<br>    &#39;AI_SERVICES&#39;,              -- Legacy umbrella (Analyst, Search, doc processing, fine-tuning)<br>    &#39;AI_FUNCTIONS&#39;,             -- Cortex AI SQL functions (newer breakout)<br>    &#39;CORTEX_AGENTS&#39;,            -- Agent orchestration<br>    &#39;CORTEX_CODE_CLI&#39;,          -- Cortex Code CLI<br>    &#39;CORTEX_CODE_SNOWSIGHT&#39;,    -- Cortex Code in Snowsight<br>    &#39;SNOWFLAKE_INTELLIGENCE&#39;    -- Snowflake Intelligence<br>)<br>AND start_time &gt; DATEADD(day, -30, CURRENT_TIMESTAMP())<br>GROUP BY 1, 2<br>ORDER BY usage_date DESC, service_type;</pre><p><strong>Important note:</strong> AI_SERVICES in METERING_HISTORY is a roll-up that includes Cortex Search serving, document processing, and AI SQL functions. The detailed views (CORTEX_SEARCH_SERVING_USAGE_HISTORY, CORTEX_DOCUMENT_PROCESSING_USAGE_HISTORY, CORTEX_AISQL_USAGE_HISTORY) give you the breakdown. Don&#39;t sum them with METERING_HISTORY — that would double-count.</p><h4>Automated Cost Alerts — Before the Bill Surprises You</h4><p>Set threshold alerts on each cost center so unusual spikes are caught within the hour, not at the end of the billing cycle:</p><pre>-- Alert: Pipeline processing cost spike<br>CREATE ALERT asset_library.monitoring.pipeline_cost_alert<br>  WAREHOUSE = asset_lib_wh<br>  SCHEDULE = &#39;60 MINUTE&#39;<br>  IF (EXISTS (<br>    SELECT 1 <br>    FROM SNOWFLAKE.ACCOUNT_USAGE.CORTEX_DOCUMENT_PROCESSING_USAGE_HISTORY<br>    WHERE start_time &gt; DATEADD(hour, -1, CURRENT_TIMESTAMP())<br>    GROUP BY 1<br>    HAVING SUM(credits_used) &gt; 5  -- threshold: 5 credits/hour for doc processing<br>  ))<br>  THEN<br>    CALL SYSTEM$SEND_EMAIL(<br>      &#39;asset_lib_notifications&#39;,<br>      &#39;admin@company.com&#39;,<br>      &#39;Asset Library: High pipeline processing cost&#39;,<br>      &#39;Document processing credit usage exceeded 5 credits in the last hour.&#39;<br>    );<br>-- Alert: Search/Agent usage cost spike  <br>CREATE ALERT asset_library.monitoring.search_cost_alert<br>  WAREHOUSE = asset_lib_wh<br>  SCHEDULE = &#39;60 MINUTE&#39;<br>  IF (EXISTS (<br>    SELECT 1 <br>    FROM SNOWFLAKE.ACCOUNT_USAGE.METERING_HISTORY<br>    WHERE service_type IN (&#39;AI_SERVICES&#39;, &#39;CORTEX_AGENTS&#39;)<br>      AND start_time &gt; DATEADD(hour, -1, CURRENT_TIMESTAMP())<br>    GROUP BY 1<br>    HAVING SUM(credits_used) &gt; 10  -- threshold: 10 credits/hour for search + agent<br>  ))<br>  THEN<br>    CALL SYSTEM$SEND_EMAIL(<br>      &#39;asset_lib_notifications&#39;,<br>      &#39;admin@company.com&#39;,<br>      &#39;Asset Library: High search/agent usage cost&#39;,<br>      &#39;Search and Agent credit usage exceeded 10 credits in the last hour. Check for unusual query volume.&#39;<br>    );</pre><h4>Measuring Answer Quality Over Time</h4><p>The thumbs-up/thumbs-down buttons in the interface aren’t just UX decoration — they’re your primary quality signal. Aggregate them weekly to track whether the library is getting better or worse:</p><pre>-- Weekly quality report<br>SELECT <br>    DATE_TRUNC(&#39;week&#39;, created_at) AS week,<br>    COUNT(*) AS total_queries,<br>    AVG(feedback_score) AS avg_satisfaction,<br>    COUNT(CASE WHEN results_returned = 0 THEN 1 END) AS zero_result_queries,<br>    COUNT(CASE WHEN feedback_score &lt;= 2 THEN 1 END) AS poor_quality_queries<br>FROM asset_library.monitoring.query_log<br>WHERE created_at &gt; DATEADD(month, -3, CURRENT_TIMESTAMP())<br>GROUP BY 1<br>ORDER BY week DESC;</pre><p>Over time, this data tells you:</p><ul><li>Which document categories produce consistently good answers</li><li>Which queries keep disappointing users — often pointing to gaps in document coverage</li><li>Where your splitting strategy is losing context and needs tuning</li><li>Whether new documents added this month improved or degraded overall quality</li></ul><h4>Guardrails — Keeping the AI Honest</h4><p>AI assistants can confidently state wrong things. For an organizational knowledge system, that’s unacceptable. These guardrails go into the agent’s system instructions to prevent the most common failure modes:</p><ol><li><strong>Topic guardrails</strong> — Only answer questions about organizational assets. Politely refuse off-topic requests.</li><li><strong>Citation requirement</strong> — Every factual claim must cite a source. If there’s no source, say “I couldn’t find relevant documents” — not a guess.</li><li><strong>Sensitivity guardrails</strong> — Never reproduce PII, client names, or pricing in responses. Point users to the source document for full details.</li><li><strong>Rate limiting</strong> — Prevent accidental or deliberate abuse via per-user query throttling.</li><li><strong>Hallucination prevention</strong> — If the search returns low-confidence results, the agent must acknowledge uncertainty explicitly rather than filling in the gaps with invention.</li></ol><p>These go in the agent’s system instructions:</p><pre>You are the Organization Asset Library assistant. Rules:<br>1. Only answer questions about organizational documents, projects, and assets.<br>2. Every factual claim must cite a specific document with its file path. <br>   If you cannot find a source, say &quot;I couldn&#39;t find relevant documents for this query.&quot;<br>3. Never reproduce sensitive information (client names, pricing, PII) in your response.<br>   Instead, point users to the source document for full details.<br>4. If a question is outside your scope, politely redirect.<br>5. When search results have low relevance, acknowledge uncertainty explicitly.</pre><h3>Layer 9: Evaluation — Proving the System Actually Works</h3><blockquote><strong><em>Business impact:</em></strong><em> Confidence that the system is actually working — not just </em>feeling<em> like it works. Automated testing catches quality problems before users notice them. You can prove to stakeholders with hard numbers that answers are accurate and grounded in real documents, not hallucinated.</em></blockquote><h4>The Challenge</h4><p>Feedback buttons tell you whether users are <em>happy</em>, but not whether answers are <em>correct</em>. A user might click “helpful” on a plausible-sounding answer that’s actually citing the wrong document. Conversely, a perfectly correct answer might get “not helpful” because the user wanted more detail.</p><p>You need systematic evaluation across three dimensions: <strong>Is the search finding the right documents?</strong> <strong>Is the agent producing faithful answers?</strong> <strong>Is quality improving or degrading over time?</strong></p><h4>Dimension 1: Search Retrieval Quality</h4><p><strong>“When someone asks a question, does the search service surface the right documents?”</strong></p><p>The foundation is a <strong>golden test set</strong> — a curated table of questions where you already know which documents should be returned:</p><pre>CREATE TABLE asset_library.eval.search_golden_set (<br>    test_id INT AUTOINCREMENT,<br>    question STRING,                 -- The test query<br>    expected_file_paths ARRAY,       -- Documents that SHOULD appear in results<br>    expected_section STRING,         -- Optional: specific section within the doc<br>    domain STRING                    -- Category for stratified analysis<br>);<br>-- Example test cases<br>INSERT INTO asset_library.eval.search_golden_set (question, expected_file_paths, domain)<br>VALUES<br>    (&#39;What automation framework did we use for the Teradata migration?&#39;,<br>     ARRAY_CONSTRUCT(&#39;migrations/teradata-framework-v2.pdf&#39;, &#39;projects/atlas/runbook.md&#39;),<br>     &#39;cloud-migration&#39;),<br>    (&#39;What is our standard resource plan for large migrations?&#39;,<br>     ARRAY_CONSTRUCT(&#39;templates/resource-plan-large.xlsx&#39;),<br>     &#39;estimation&#39;);</pre><p><strong>Run automated retrieval tests</strong> using SNOWFLAKE.CORTEX.SEARCH_PREVIEW to query the search service directly from SQL:</p><pre>-- Test retrieval: query search and check if expected docs appear in results<br>WITH test_results AS (<br>    SELECT <br>        g.test_id,<br>        g.question,<br>        g.expected_file_paths,<br>        PARSE_JSON(<br>            SNOWFLAKE.CORTEX.SEARCH_PREVIEW(<br>                &#39;ASSET_LIBRARY.SEARCH.DOCUMENT_SEARCH&#39;,<br>                OBJECT_CONSTRUCT(<br>                    &#39;query&#39;, g.question,<br>                    &#39;columns&#39;, ARRAY_CONSTRUCT(&#39;file_path&#39;, &#39;chunk_text&#39;, &#39;document_title&#39;),<br>                    &#39;limit&#39;, 5<br>                )::STRING<br>            )<br>        ) AS raw_results<br>    FROM asset_library.eval.search_golden_set g<br>)<br>SELECT <br>    test_id,<br>    question,<br>    -- Hit@1: Is the top result one of the expected documents?<br>    ARRAY_CONTAINS(<br>        raw_results:results[0]:file_path::STRING, <br>        expected_file_paths<br>    ) AS hit_at_1,<br>    -- Hit@3: Does any of the top 3 results match?<br>    (ARRAY_CONTAINS(raw_results:results[0]:file_path::STRING, expected_file_paths) OR<br>     ARRAY_CONTAINS(raw_results:results[1]:file_path::STRING, expected_file_paths) OR<br>     ARRAY_CONTAINS(raw_results:results[2]:file_path::STRING, expected_file_paths)<br>    ) AS hit_at_3<br>FROM test_results;</pre><p><strong>Aggregate into a retrieval quality scorecard:</strong></p><pre>-- Overall retrieval quality score<br>SELECT <br>    COUNT(*) AS total_tests,<br>    ROUND(AVG(hit_at_1::INT) * 100, 1) AS hit_rate_at_1_pct,<br>    ROUND(AVG(hit_at_3::INT) * 100, 1) AS hit_rate_at_3_pct,<br>    COUNT(CASE WHEN NOT hit_at_3 THEN 1 END) AS failed_tests<br>FROM retrieval_test_results;</pre><p><strong>Target:</strong> Hit Rate@3 above 85% means the search is working well. A score below 70% means your chunking strategy or search configuration needs tuning.</p><h4>Dimension 2: Agent Answer Quality — Built-in Cortex Agent Evaluations</h4><p><strong>“Given the right documents, is the agent producing correct, faithful answers?”</strong></p><p>Snowflake provides a native evaluation framework that scores agent responses using LLM judges — both built-in metrics and custom ones you define.</p><p><strong>Step 1: Create an evaluation dataset.</strong></p><p>Each row is a test question with optional ground truth describing the expected behavior:</p><pre>CREATE TABLE asset_library.eval.agent_eval_data (<br>    input_query VARCHAR,<br>    ground_truth VARIANT<br>);<br>-- Insert test cases with expected answer content<br>INSERT INTO asset_library.eval.agent_eval_data VALUES<br>    (&#39;What reference architecture did we use for Teradata migrations?&#39;,<br>     PARSE_JSON(&#39;{<br>         &quot;ground_truth_output&quot;: &quot;The answer should reference the 4-phase approach (Assessment, Design, Migration, Validation) from the Teradata-to-Snowflake Migration Framework v2.1, and cite the file path migrations/teradata-framework-v2.pdf&quot;<br>     }&#39;)),<br>    (&#39;What is the standard team composition for a 12-week migration?&#39;,<br>     PARSE_JSON(&#39;{<br>         &quot;ground_truth_output&quot;: &quot;Should reference 2 architects, 4 engineers, 1 PM from the Resource Planning Template, citing templates/resource-plan-large.xlsx&quot;<br>     }&#39;));</pre><p><strong>Step 2: Register the dataset.</strong></p><pre>CALL SYSTEM$CREATE_EVALUATION_DATASET(<br>    &#39;Cortex Agent&#39;,<br>    &#39;ASSET_LIBRARY.EVAL.AGENT_EVAL_DATA&#39;,<br>    &#39;ASSET_LIBRARY.EVAL.DOC_AGENT_EVALSET&#39;,<br>    OBJECT_CONSTRUCT(<br>        &#39;query_text&#39;, &#39;INPUT_QUERY&#39;,<br>        &#39;expected_tools&#39;, &#39;GROUND_TRUTH&#39;<br>    )<br>);</pre><p><strong>Step 3: Define evaluation metrics in YAML.</strong></p><p>Upload this config to a stage (@asset_library.eval.config/agent_eval.yaml):</p><pre>evaluation:<br>  agent_params:<br>    agent_name: &quot;DOC_AGENT&quot;<br>    agent_type: &quot;CORTEX AGENT&quot;<br>    database: &quot;ASSET_LIBRARY&quot;<br>    schema: &quot;APP&quot;<br>  source_metadata:<br>    type: &quot;dataset&quot;<br>    dataset_name: &quot;ASSET_LIBRARY.EVAL.DOC_AGENT_EVALSET&quot;<br>metrics:<br>  # Built-in: does the answer match expected ground truth?<br>  - &quot;answer_correctness&quot;<br>  # Built-in: is the reasoning internally consistent?<br>  - &quot;logical_consistency&quot;<br>  # Custom: is the answer grounded in retrieved sources?<br>  - name: &quot;faithfulness&quot;<br>    score_ranges:<br>      min_score: [1, 3]<br>      median_score: [4, 6]<br>      max_score: [7, 10]<br>    prompt: |<br>      Evaluate whether the agent&#39;s response is fully grounded in the documents it retrieved.<br>      A faithful response only states things supported by its cited sources.<br>      An unfaithful response invents details, extrapolates beyond what sources say, or<br>      attributes claims to documents that don&#39;t contain them.<br>      User query: {{input}}<br>      Agent response: {{output}}<br>      Tools used and their results: {{tool_info}}<br>      Score 1-10:<br>      1-3: Major hallucinations or unsupported claims<br>      4-6: Mostly grounded but some claims lack source support<br>      7-10: Every claim is directly supported by cited documents<br>  # Custom: are the retrieved documents relevant?<br>  - name: &quot;retrieval_relevance&quot;<br>    score_ranges:<br>      min_score: [1, 3]<br>      median_score: [4, 6]<br>      max_score: [7, 10]<br>    prompt: |<br>      Evaluate how relevant the retrieved documents were to the user&#39;s question.<br>      User query: {{input}}<br>      Search results and tool execution: {{tool_info}}<br>      Score 1-10:<br>      1-3: Retrieved documents are unrelated to the question<br>      4-6: Some retrieved documents are relevant, others are noise<br>      7-10: Retrieved documents directly address the question</pre><p><strong>Step 4: Run the evaluation.</strong></p><pre>CALL EXECUTE_AI_EVALUATION(<br>    &#39;START&#39;,<br>    OBJECT_CONSTRUCT(&#39;run_name&#39;, &#39;baseline-eval-2026-07-30&#39;),<br>    &#39;@asset_library.eval.config/agent_eval.yaml&#39;<br>);<br>-- Check progress<br>CALL EXECUTE_AI_EVALUATION(<br>    &#39;STATUS&#39;,<br>    OBJECT_CONSTRUCT(&#39;run_name&#39;, &#39;baseline-eval-2026-07-30&#39;),<br>    &#39;@asset_library.eval.config/agent_eval.yaml&#39;<br>);</pre><p><strong>Step 5: Analyze results.</strong></p><pre>-- View scores by metric<br>SELECT <br>    METRIC_NAME,<br>    ROUND(AVG(EVAL_AGG_SCORE), 2) AS avg_score,<br>    MIN(EVAL_AGG_SCORE) AS min_score,<br>    MAX(EVAL_AGG_SCORE) AS max_score,<br>    COUNT(*) AS test_cases<br>FROM TABLE(SNOWFLAKE.LOCAL.GET_AI_EVALUATION_DATA(<br>    &#39;ASSET_LIBRARY&#39;, &#39;APP&#39;, &#39;DOC_AGENT&#39;, &#39;CORTEX AGENT&#39;, &#39;baseline-eval-2026-07-30&#39;<br>))<br>GROUP BY METRIC_NAME<br>ORDER BY avg_score;<br>-- Drill into failures: which questions scored poorly?<br>SELECT <br>    INPUT AS question,<br>    METRIC_NAME,<br>    EVAL_AGG_SCORE AS score,<br>    METRIC_CALLS[0]:explanation::STRING AS why_it_scored_low<br>FROM TABLE(SNOWFLAKE.LOCAL.GET_AI_EVALUATION_DATA(<br>    &#39;ASSET_LIBRARY&#39;, &#39;APP&#39;, &#39;DOC_AGENT&#39;, &#39;CORTEX AGENT&#39;, &#39;baseline-eval-2026-07-30&#39;<br>))<br>WHERE EVAL_AGG_SCORE &lt; 5<br>ORDER BY EVAL_AGG_SCORE;</pre><h4>Dimension 3: Production Monitoring with Observability Events</h4><p><strong>“What’s actually happening when real users ask questions?”</strong></p><p>Every agent interaction — including tool calls, search results, and user feedback — is automatically traced. Query these events to understand production behavior:</p><pre>-- Retrieve all user feedback for the asset library agent<br>SELECT <br>    TIMESTAMP,<br>    VALUE:feedback_score::INT AS score,<br>    VALUE:feedback_text::STRING AS comment,<br>    RECORD_ATTRIBUTES:&quot;snow.ai.request_id&quot;::STRING AS request_id<br>FROM TABLE(SNOWFLAKE.LOCAL.GET_AI_OBSERVABILITY_EVENTS(<br>    &#39;ASSET_LIBRARY&#39;, &#39;APP&#39;, &#39;DOC_AGENT&#39;, &#39;CORTEX AGENT&#39;<br>))<br>WHERE RECORD:name = &#39;CORTEX_AGENT_FEEDBACK&#39;<br>ORDER BY TIMESTAMP DESC;<br>-- Find queries where the agent couldn&#39;t find relevant results<br>SELECT <br>    TIMESTAMP,<br>    VALUE:input::STRING AS user_question,<br>    VALUE:output::STRING AS agent_response<br>FROM TABLE(SNOWFLAKE.LOCAL.GET_AI_OBSERVABILITY_EVENTS(<br>    &#39;ASSET_LIBRARY&#39;, &#39;APP&#39;, &#39;DOC_AGENT&#39;, &#39;CORTEX AGENT&#39;<br>))<br>WHERE RECORD:name = &#39;CORTEX_AGENT_RESPONSE&#39;<br>  AND VALUE:output::STRING ILIKE &#39;%couldn&#39;&#39;t find%&#39;<br>ORDER BY TIMESTAMP DESC;</pre><h4>Automated Regression Testing — Catch Degradation Before Users Do</h4><p>Schedule the full evaluation to run weekly. If scores drop below a threshold, an alert fires before users notice:</p><pre>-- Weekly automated evaluation<br>CREATE TASK asset_library.eval.weekly_evaluation<br>    WAREHOUSE = asset_lib_wh<br>    SCHEDULE = &#39;USING CRON 0 6 * * MON America/New_York&#39;<br>AS<br>    CALL EXECUTE_AI_EVALUATION(<br>        &#39;START&#39;,<br>        OBJECT_CONSTRUCT(&#39;run_name&#39;, CONCAT(&#39;weekly-&#39;, CURRENT_DATE()::STRING)),<br>        &#39;@asset_library.eval.config/agent_eval.yaml&#39;<br>    );<br>ALTER TASK asset_library.eval.weekly_evaluation RESUME;</pre><p><strong>Compare quality across runs</strong> to detect regressions when you change chunking strategies, update agent instructions, or add new documents:</p><pre>-- Compare two evaluation runs side by side<br>WITH baseline AS (<br>    SELECT METRIC_NAME, AVG(EVAL_AGG_SCORE) AS score<br>    FROM TABLE(SNOWFLAKE.LOCAL.GET_AI_EVALUATION_DATA(<br>        &#39;ASSET_LIBRARY&#39;, &#39;APP&#39;, &#39;DOC_AGENT&#39;, &#39;CORTEX AGENT&#39;, &#39;baseline-eval-2026-07-30&#39;<br>    ))<br>    GROUP BY METRIC_NAME<br>),<br>current_run AS (<br>    SELECT METRIC_NAME, AVG(EVAL_AGG_SCORE) AS score<br>    FROM TABLE(SNOWFLAKE.LOCAL.GET_AI_EVALUATION_DATA(<br>        &#39;ASSET_LIBRARY&#39;, &#39;APP&#39;, &#39;DOC_AGENT&#39;, &#39;CORTEX AGENT&#39;, &#39;weekly-2026-08-06&#39;<br>    ))<br>    GROUP BY METRIC_NAME<br>)<br>SELECT <br>    b.METRIC_NAME,<br>    ROUND(b.score, 2) AS baseline_score,<br>    ROUND(c.score, 2) AS current_score,<br>    ROUND(c.score - b.score, 2) AS delta,<br>    CASE WHEN c.score &lt; b.score - 0.5 THEN &#39;⚠️ REGRESSION&#39; ELSE &#39;✓ OK&#39; END AS status<br>FROM baseline b<br>JOIN current_run c ON b.METRIC_NAME = c.METRIC_NAME;</pre><h4>What Good Looks Like — Target Metrics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7b5RPyLoPMHK7lyvQ4ib0Q.png" /><figcaption>Figure 7: Evaluation Results (Sample)(Image credit : Author)</figcaption></figure><p>When a metric drops below its red flag threshold, investigate:</p><ul><li><strong>Low retrieval relevance</strong> → Chunking strategy isn’t preserving enough context, or scoring weights need tuning</li><li><strong>Low faithfulness</strong> → Agent instructions need stronger grounding requirements, or search is returning irrelevant chunks that confuse the model</li><li><strong>Low answer correctness</strong> → Missing documents in the library (coverage gap), or stale content that no longer matches reality</li><li><strong>High zero-result rate</strong> → Users are asking about topics not covered in your document library — time to expand coverage</li></ul><h4>How It All Fits Together</h4><p>The eight layers form a single end-to-end pipeline: documents flow in from your existing storage, are intelligently processed and classified, become searchable through a managed AI-powered index, and surface as plain-language answers through a web interface — all governed by access controls and observable through monitoring dashboards.</p><p>Here’s the complete picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQY4m6DiGTjWHVcbLLE8BQ.png" /><figcaption>Figure 8: Detailed Architecture (Image credit : Author)</figcaption></figure><h4>Your Implementation Roadmap — From Proof to Production</h4><p>This doesn’t need to be a six-month project. Here’s a phased approach that delivers business value at every step:</p><p><strong>Phase 1 — Prove the concept</strong> <em>(deliver a working demo in days, not weeks)</em></p><ul><li>Pick one document source (e.g., your architecture docs folder)</li><li>Load 50–100 documents into a Snowflake stage</li><li>Parse, chunk (type-aware), and create a Cortex Search Service</li><li>Build a minimal Streamlit chat interface</li><li>Validate with 5–10 real user queries — let stakeholders try it</li></ul><p><strong>Phase 2 — Add intelligence</strong> <em>(make answers smarter and more trustworthy)</em></p><ul><li>Implement AI_CLASSIFY for automatic sensitivity and domain tagging</li><li>Add time decay and popularity boosts to surface the best results</li><li>Build the Cortex Agent with citations and guardrails</li><li>Add user feedback collection so you can measure quality</li></ul><p><strong>Phase 3 — Scale and govern</strong> <em>(ready for the whole organization)</em></p><ul><li>Connect all document sources (Box, Git, Google Drive)</li><li>Implement stream-triggered incremental pipeline — new docs searchable within minutes</li><li>Set up RBAC with separate search services by access tier</li><li>Deploy cost monitoring and automated alerts</li></ul><p><strong>Phase 4 — Optimize continuously</strong> <em>(improve based on real usage data)</em></p><ul><li>Analyze feedback data to improve splitting strategies for underperforming document types</li><li>Tune boost/decay weights based on what users actually find useful</li><li>Expand to new document types and sources as the library grows</li><li>Build domain-specific scoring profiles for different teams (e.g., sales vs. engineering)</li></ul><h4>What This Means for Your Organization</h4><p>Before the numbers and the roadmap, here’s what this system delivers in plain business terms:</p><p><strong>Time recovered.</strong> If 50 consultants each save 2 hours per week no longer digging through folders, pinging colleagues, or re-creating assets that already exist — that’s 5,200 recovered billable hours per year. Even at a modest billing rate, that’s real revenue that was previously lost to friction.</p><p><strong>Faster onboarding.</strong> New hires stop asking “Where do I find…?” on day one. They ask the system instead and get the same quality answers as a 10-year veteran. The ramp-up period shrinks from weeks to days because institutional knowledge is no longer locked in people’s heads.</p><p><strong>Knowledge that doesn’t walk out the door.</strong> When a senior architect leaves, their project decisions, design rationale, and lessons learned stay in the library — searchable by whoever picks up their work next. Employee turnover stops being a knowledge crisis.</p><p><strong>Risk reduction.</strong> Sensitive documents are classified and access-controlled automatically. Your compliance team can audit exactly who searched for what and when. No more “we think only the right people can see this” — the platform enforces it.</p><p><strong>Measurable ROI.</strong> Every credit spent on the system is tracked. Every question asked is logged. You can show your CFO a dashboard that says: “400 queries this week, 85% satisfaction rate, $X in Snowflake credits.” The value is visible, not assumed.</p><p><strong>No lock-in, no migration risk.</strong> Documents stay where they are — Box, Google Drive, S3. Snowflake connects to them without copying. If you ever want to stop, your documents haven’t moved. You’re not betting the company on a new storage silo.</p><h4>Final Thoughts</h4><p>The technology stack to build this is available today — AI_PARSE_DOCUMENT for extraction, Cortex Search for hybrid retrieval with smart ranking, Cortex Agents for conversational access, and Streamlit in Snowflake for the interface. Nothing here requires a research project or a specialized AI team.</p><p>The hard part isn’t the technology. It’s the discipline.</p><p>Discipline to split documents according to their natural structure — not with a generic tokenizer that destroys context. Discipline to classify content before indexing, so sensitive information is controlled, not assumed. Discipline to monitor quality week over week, and improve based on what users actually experience.</p><p>But here’s what that discipline buys you: your organization’s collective knowledge — years of hard-won project experience, battle-tested architectures, proven estimation models, lessons from past mistakes — becomes accessible to every person who needs it. Not buried in a folder. Not locked in someone’s head. Available in seconds, through a plain-language question.</p><p>New employees ramp up faster. Senior people spend less time answering the same questions. Proposals get written with institutional knowledge behind them. Solutions that were built before get reused instead of rebuilt.</p><p>No more digging through folders. No more re-inventing what your team already built. No more “ask Amy, she might remember.”</p><p><strong>Your organization’s knowledge finally works for you.</strong></p><p><strong>Now, You Know What To Do!</strong></p><ul><li><strong>Please share</strong> this with anyone who you think will be interested. It might help them, and it really helps me!</li><li>Please <strong>give me 50 claps</strong>! (Just hold down the clap button.)</li><li>Feel free to <strong>leave a comment</strong> 💬.</li><li>🙏 If you found this article helpful, <strong>subscribe and hit it</strong>. <a href="https://medium.com/@singh.sanjiv"><strong><em>Follow</em></strong></a><strong> </strong>— it helps more people discover it.</li><li>🌱 Good ideas tend to spread. I truly appreciate it when readers pass them along.</li></ul><p><em>All Snowflake features referenced in this blog — AI_PARSE_DOCUMENT, Cortex Search (with numeric boosts, time decay, scoring profiles, and component weights), Cortex Agents, AI_CLASSIFY, Streamlit in Snowflake, Snowflake Tasks with streams, and staged file ingestion — are documented capabilities available today. For the latest availability and regional support, consult the </em><a href="https://docs.snowflake.com/"><em>Snowflake Documentation</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d8275141861" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MCP and Cortex Code(CoCo): Expanding LLM Agent Boundaries]]></title>
            <link>https://medium.com/@singh.sanjiv/mcp-and-cortex-code-coco-expanding-llm-agent-boundaries-e044e839f865?source=rss-30311cf4ee3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/e044e839f865</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[Sanjiv Singh]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 06:10:56 GMT</pubDate>
            <atom:updated>2026-07-22T06:10:56.232Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to building deterministic AI agent workflows using the Model Context Protocol</em></p><h4>So, what’s the problem? AI is already smart, right?</h4><p>Yes — but smart doesn’t mean connected.</p><p>Today’s <strong>AI models </strong>(Claude, GPT, Mistral, etc.) are incredibly good at reasoning. But they live inside a box. They can think, but they can’t <strong>do</strong> anything in your actual business systems. They would not be able to check your Jira tickets. They can’t read your GitHub repos. They can’t create tables in Snowflake. Not on their own.</p><p>To make AI actually useful in enterprise workflows, engineers have been building custom integrations — one for Jira, another for GitHub, another for Snowflake, another for Slack. Every AI tool paired with every business system needs its own connector. If you have 5 AI models and 5 business tools, that’s <strong>25 custom integrations</strong> to build and maintain.</p><p>This is the <strong>N x M problem</strong>. And it doesn’t scale.</p><p><strong>Assumptions for this blog:</strong></p><ul><li>You know what LLMs (Large Language Models) are — they power ChatGPT, Claude, etc.</li><li>You don’t need to know how tool-calling works internally — we’ll explain that</li><li>You’re interested in making AI agents do real work (not just chat)</li></ul><h4>OK, so how do we fix the N x M problem?</h4><p>This is exactly where <strong>MCP</strong> comes in.</p><h3>What is MCP?</h3><p><strong>MCP</strong> stands for <strong>Model Context Protocol</strong>. It’s an open-source standard that gives AI agents a universal way to talk to any external system — databases, APIs, file systems, project management tools — through a single, consistent interface.</p><p>Think of it this way:</p><blockquote><em>“MCP offers a common, open standard that makes these connections easier, much like how a USB-C port makes connecting devices simple.”</em> — <strong>Google Cloud</strong></blockquote><p>Before USB-C, every phone manufacturer had its own charging cable. MCP does for AI what USB-C did for devices: <strong>one standard plug that works everywhere</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*nIkEb3C45R8kEEe5K3EoYA.png" /><figcaption>Figure 1: Before and After MCP(Source : Snowflake )</figcaption></figure><h4>Why does MCP matter?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*6-6Hsr8XGFNJ8lx5mexPag.png" /></figure><h4>A brief history of MCP</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*eBoZoPGBYmGb4RlTouHi0w.png" /></figure><h4>Who supports MCP today?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*RUC1-lw3ETU3HddBdDQelw.png" /></figure><h4>OK, I get why. But how does MCP actually work?</h4><p>Great question. Let’s break it into three layers.</p><p>T<strong>he Architecture: Host → Client → Server → Tool</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*BTgSsPMnrpIh-xWPbEdhAg.png" /><figcaption>Figure 2: MCP Overview (Source : Snowflake)</figcaption></figure><p><strong>Three roles:</strong></p><ol><li><strong>MCP Host</strong> — The application you’re working in (Cortex Code CLI, Cursor, Claude Desktop, IBM BOB). It holds the AI model and manages conversations.</li><li><strong>MCP Client</strong> — Lives inside the Host. Each Client maintains a 1:1 connection to one MCP Server. The Host can have many Clients.</li><li><strong>MCP Server</strong> — A lightweight program that exposes tools to the AI. It connects to the actual business system (Jira, GitHub, Snowflake, etc.)</li></ol><h4>What does an MCP Server expose?</h4><p>Every MCP Server can offer three types of capabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*FVgfSoltZtNmnK-yWK663A.png" /><figcaption>Figure 3 : MCP capabilities( Image Credit Author)</figcaption></figure><h4>Key Features of MCP</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*-rnFrqJ7QSNKt1I7nYxaVw.png" /><figcaption>Figure 4: MCP Features( Image Credit Author)</figcaption></figure><h4>How does this help me build a real AI workflow — one that behaves predictably?</h4><p>This is where it gets powerful. Let’s talk about <strong>deterministic agentic workflows</strong>.</p><h4>The Problem with “Smart” AI</h4><p>If you just give an AI model access to tools and say “<em>go migrate my database,”</em> it might:</p><ul><li>Call tools in the wrong order</li><li>Skip validation steps</li><li>Forget to update the Jira ticket</li><li>Create tables that already exist (and overwrite your data!)</li></ul><p>You need <strong>deterministic behavior</strong> — the agent follows a recipe every single time.</p><h4>The Solution: AGENTS.md + MCP Tools</h4><p>Here’s the pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*fLmARtSswpKQAdKx24oypQ.png" /><figcaption>Figure 5: How Agentic Solution works( Image Credit Author)</figcaption></figure><p><strong>Three ingredients for deterministic agent workflows:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*eECNa4CWyhuIOC9_FHObwA.png" /><figcaption>Figure 6: Components ( Image Credit Author)</figcaption></figure><p>The AI isn’t improvising. It’s following your <strong>AGENTS.md</strong> playbook while using MCP tools as its hands. Same input, same output, every time.</p><h4>What does AGENTS.md actually look like?</h4><p>Here’s a trimmed snippet from the actual AGENTS.md in this project:</p><pre># Teradata-to-Snowflake DDL Auto-Conversion Pipeline<br>## Overview<br>This project provides an automated workflow that converts Teradata DDL<br>definitions to Snowflake DDL, driven by Jira tasks. The pipeline uses<br>MCP tools to orchestrate across Jira, GitHub Enterprise, and Snowflake.<br><br>## Workflow Steps<br>When asked to run the DDL conversion pipeline (or similar phrasing like<br>&quot;convert DDL&quot;, &quot;process pending tasks&quot;, &quot;run migration pipeline&quot;),<br>execute the following steps in order:<br><br>### Step 1: Find Pending Jira Task<br>Use tool `get_jira_pending_tasks` to find one pending task assigned<br>to the current user.<br><br>### Step 2: Extract Table Names<br>Parse the task description to extract table names. Table names are<br>listed in the description as bullet points in `database.table_name` format.<br>### Step 3: Get Teradata DDL from GitHub<br>Use tool `get_github_file_content` to retrieve the Teradata DDL for each table:<br>- repo: `git-repo/snowflake-git-integration`<br>- file_path: `ddl/{table_name}.sql`<br>- ref: `main`<br><br>### Step 4: Convert to Snowflake DDL<br>Convert each Teradata DDL to Snowflake-compatible DDL by:<br>- Removing `MULTISET` / `SET` table keywords<br>- Removing `NO FALLBACK`, `NO BEFORE JOURNAL`, `NO AFTER JOURNAL`<br>- Removing `CHARACTER SET LATIN NOT CASESPECIFIC`<br>- Removing `FORMAT &#39;YYYY-MM-DD&#39;` on DATE columns<br>- Removing `PRIMARY INDEX`, `UNIQUE PRIMARY INDEX`<br>- Using `CREATE TABLE IF NOT EXISTS` with target `AI_MCP_TEST.PUBLIC`<br>### Step 5: Attach Snowflake DDL to Jira<br>…<br>### Step 6: Create Tables in Snowflake<br>…<br>### Step 7: Mark Task Completed<br>…</pre><p>This file lives in your project root and is <strong>automatically injected as system context</strong> into every agent session. The agent reads it before doing anything — it’s the playbook that ensures deterministic behavior regardless of which human runs the command.</p><h3>Show me a real use case. Walk me through the whole story.</h3><p>Let’s walk through a complete, production-grade scenario: <strong>Automated Teradata-to-Snowflake DDL Migration</strong>.</p><p><strong>The Story: How a Project Manager Sets This Up</strong></p><p>Meet <strong>Amy</strong>. She’s a Project Manager at a company migrating their data warehouse from Teradata to Snowflake. Her team has 400+ tables to migrate.</p><p>The old process looked like this:</p><ol><li>Amy creates a Jira ticket listing which tables to migrate</li><li>A developer picks up the ticket, opens GitHub, and finds the Teradata DDL</li><li>The developer manually rewrites the DDL for Snowflake (removing Teradata-specific syntax)</li><li>They open a SQL client and run the DDL in Snowflake</li><li>They manually check if the columns look right</li><li>They update the Jira ticket with what they did</li><li>They mark the ticket Done</li></ol><p><strong>Per table: ~30 minutes. For 400 tables: weeks of tedious, error-prone work.</strong></p><p>Amy decides to set things up differently. Here’s what she does:</p><h4>What Amy Sets Up (One-Time)</h4><p><strong>Step A: Source code goes to GitHub</strong></p><p>All existing Teradata DDL files are already in a GitHub repo (git-repo/snowflake-git-integration) in the ddl/ folder. Each file is named by its fully qualified table name:</p><pre>ddl/<br>├── analytics_db.stg_web_logs.sql<br>├── analytics_db.stg_web_sessions.sql<br>├── warehouse_db.fact_orders.sql<br>├── workforce_db.stg_payroll.sql<br>└── … (400+ files)</pre><p><strong>Step B: Jira tickets describe the work</strong></p><p>Amy creates Jira stories with the label TD_TO_SNOW. In each ticket’s description, she lists the tables to migrate as bullet points:</p><pre>Tables to migrate:<br>- analytics_db.stg_web_logs<br>- analytics_db.stg_web_sessions</pre><p>That’s it. No special formatting. Just table names.</p><p><strong>Step C: Two MCP Servers get deployed</strong></p><ol><li>A <strong>Custom MCP Server</strong> (Python, running locally) that can talk to Jira and GitHub</li><li>A <strong>Snowflake Managed MCP Server</strong> (pure SQL, zero infrastructure) that can run DDL, validate tables, and estimate costs</li></ol><p><strong>Step D: AGENTS.md defines the workflow</strong></p><p>An AGENTS.md file is placed in the project repo. It tells the AI agent exactly what to do, step by step, when someone says “run the migration pipeline.”</p><h4>What the Developer Does (Every Day)</h4><p>The developer opens their terminal. Type one line:</p><pre>&gt; Run the migration pipeline for pending tickets</pre><p>The AI agent (Cortex Code CLI or IBM BOB) reads the AGENTS.md file and executes the workflow autonomously. Here’s what happens behind the scenes:</p><h3>What Amy (Project Manager) sees</h3><p>She checks Jira the next morning:</p><ul><li>Tickets are moving from <em>“To Do” → “Done”</em> automatically</li><li>Each completed ticket has two attachments:snowflake_ddl_2025–06–30.sql — the converted DDLmigration_report_2025–06–30.md — table mapping, cost tier, validation status</li><li>The completion comment says exactly what was done and when</li><li>Partially-failed tickets stay “<strong>In Progress</strong>” so she knows to investigate</li></ul><p>She queries the MIGRATION_LOG table in Snowflake for an executive dashboard:</p><pre>SELECT STATUS, COUNT(*) as TABLE_COUNT, COST_TIER<br>FROM AI_MCP_TEST.MCP_DEMO.MIGRATION_LOG<br>GROUP BY STATUS, COST_TIER;</pre><h4>How do you build the Custom MCP Server?</h4><p>Let’s look at the actual code. We use <strong>FastMCP</strong> (a Python framework) to create lightweight MCP servers.</p><p><strong>Jira MCP Server (mcp/jira_mcp_server.py)</strong></p><p>This server exposes tools for Jira ticket management:</p><pre>from fastmcp import FastMCP<br>mcp = FastMCP(<br>    &quot;jira-mcp&quot;,<br>    instructions=&quot;Manage Jira tasks for migration ticket management.&quot;<br>)<br>@mcp.tool()<br>def get_jira_pending_tasks(<br>  project_key: str | None = None,<br>  assignee: str = &quot;currentUser()&quot;,<br>  max_results: int = 20,<br>) -&gt; str:<br>  &quot;&quot;&quot;Get pending Jira tasks (To Do and In Progress) from Jira Cloud.<br>  Args:<br>  project_key: Optional Jira project key to filter by (e.g., &#39;ENG&#39;)<br>  assignee: Jira assignee - use &#39;currentUser()&#39; for authenticated user<br>  max_results: Maximum number of issues to return (default 20)<br>  &quot;&quot;&quot;<br>  # Build JQL query - filters by status and label<br>  jql_parts = [&#39;status IN (&quot;To Do&quot;, &quot;In Progress&quot;)&#39;]<br>  if project_key:<br>    jql_parts.append(f&quot;project = {project_key}&quot;)<br>  if assignee:<br>    jql_parts.append(f&quot;assignee = {assignee}&quot;)<br><br>  jql = &quot; AND &quot;.join(jql_parts) + &quot; AND labels = TD_TO_SNOW ORDER BY updated DESC&quot;<br>  # Call Jira REST API<br>  url = f&quot;{base_url}/rest/api/3/search/jql&quot;<br>  response = requests.post(url, headers=headers, json={<br>    &quot;jql&quot;: jql,<br>    &quot;maxResults&quot;: max_results,<br>    &quot;fields&quot;: [&quot;summary&quot;, &quot;description&quot;, &quot;status&quot;, &quot;priority&quot;]<br>  })<br>  # Return structured results<br>  return json.dumps({&quot;total&quot;: total, &quot;issues&quot;: issues})<br><br>@mcp.tool()<br>def add_jira_attachment(issue_key: str, content: str, filename: str) -&gt; str:<br>  &quot;&quot;&quot;Add text content as a file attachment to a Jira issue.<br>  Args:<br>  issue_key: The Jira issue key (e.g., &#39;MIG-142&#39;)<br>  content: The text content to attach as a file<br>  filename: Name for the attached file<br>  &quot;&quot;&quot;<br>  response = requests.post(<br>    f&quot;{base_url}/rest/api/3/issue/{issue_key}/attachments&quot;,<br>    headers={&quot;X-Atlassian-Token&quot;: &quot;no-check&quot;},<br>    files={&quot;file&quot;: (filename, content.encode(&quot;utf-8&quot;), &quot;text/plain&quot;)},<br>  )<br>  return json.dumps({&quot;success&quot;: True, &quot;issue_key&quot;: issue_key, &quot;filename&quot;: filename})<br><br>@mcp.tool()<br>def complete_jira_task(issue_key: str, comment: str = &quot;&quot;) -&gt; str:<br>  &quot;&quot;&quot;Transition a Jira issue to Done and optionally add a comment.<br>  Args:<br>  issue_key: The Jira issue key (e.g., &#39;MIG-142&#39;)<br>  comment: Comment to add when completing the task<br>  &quot;&quot;&quot;<br>  # Step 1: Find the &quot;Done&quot; transition<br>  transitions = requests.get(f&quot;{base_url}/rest/api/3/issue/{issue_key}/transitions&quot;)<br>  done_transition = find_done_transition(transitions)<br>  # Step 2: Execute the transition<br>  requests.post(f&quot;{base_url}/rest/api/3/issue/{issue_key}/transitions&quot;,<br>  json={&quot;transition&quot;: {&quot;id&quot;: done_transition[&quot;id&quot;]}})<br>  # Step 3: Add comment<br>  if comment:<br>    requests.post(f&quot;{base_url}/rest/api/3/issue/{issue_key}/comment&quot;,<br>    json={&quot;body&quot;: {&quot;type&quot;: &quot;doc&quot;, &quot;content&quot;: […]}})<br>    return json.dumps({&quot;success&quot;: True, &quot;issue_key&quot;: issue_key})<br><br># Start the server on port 8000<br>if __name__ == &quot;__main__&quot;:<br>   mcp.run(transport=&quot;http&quot;, host=&quot;0.0.0.0&quot;, port=8000)<br><br></pre><p><strong>GitHub MCP Server (mcp/git_mcp_server.py)</strong><br>This server fetches source DDL files from the repository:</p><pre><br>from fastmcp import FastMCP<br>mcp = FastMCP(<br>&quot;git-mcp&quot;,<br>instructions=&quot;Fetch file content from GitHub repositories.&quot;<br>)<br>@mcp.tool()<br>def get_github_file_content(<br>repo: str,<br>file_path: str,<br>ref: str = &quot;main&quot;,<br>github_base_url: str = &quot;https://github.ibm.com&quot;,<br>) -&gt; str:<br>  &quot;&quot;&quot;Get the content of a file from a GitHub repository.<br>  Args:<br>  repo: Repository in &#39;owner/repo&#39; format<br>  file_path: Relative path to the file (e.g., &#39;ddl/analytics_db.stg_web_logs.sql&#39;)<br>  ref: Branch, tag, or commit SHA (default &#39;main&#39;)<br>  github_base_url: Base URL of the GitHub instance<br>  &quot;&quot;&quot;<br>  headers = {<br>  &quot;Accept&quot;: &quot;application/vnd.github.v3.raw&quot;,<br>  &quot;Authorization&quot;: f&quot;token {github_token}&quot;,<br>  }<br>  url = f&quot;{github_base_url}/api/v3/repos/{repo}/contents/{file_path}&quot;<br>  response = requests.get(url, headers=headers, params={&quot;ref&quot;: ref})<br>  return json.dumps({<br>    &quot;repo&quot;: repo,<br>    &quot;file_path&quot;: file_path,<br>    &quot;content&quot;: response.text,<br>  })<br># Start the server on port 8001<br>if __name__ == &quot;__main__&quot;:<br>mcp.run(transport=&quot;http&quot;, host=&quot;0.0.0.0&quot;, port=8001)</pre><h4>Register the Custom MCP Servers</h4><pre># Start the servers<br>python mcp/jira_mcp_server.py &amp; # runs on port 8000<br>python mcp/git_mcp_server.py &amp; # runs on port 8001<br># Register with Cortex Code CLI<br>cortex mcp add jira-mcp http://localhost:8000/mcp - transport http<br>cortex mcp add git-mcp http://localhost:8001/mcp - transport http<br># Verify registration<br>cortex mcp list</pre><p><strong>Key design points:</strong></p><ul><li><strong>Each tool has a clear docstring</strong> — the AI reads this to understand what the tool does</li><li>Arguments are flat and simple (no deep nesting)</li><li><strong>Returns JSON strings</strong> — structured, parseable responses</li><li><strong>Single responsibility</strong> — one tool does one job</li></ul><h4>What about the Snowflake Managed MCP Server?</h4><p>This is where it gets even easier. With Snowflake’s Managed MCP Server, you don’t deploy any infrastructure. You define tools using SQL DDL, and Snowflake hosts the server for you.</p><h4>Creating the Managed MCP Server</h4><pre>-- Step 1: Create an audit log table<br>CREATE TABLE IF NOT EXISTS AI_MCP_TEST.MCP_DEMO.MIGRATION_LOG (<br>    ENTITY_NAME VARCHAR NOT NULL,<br>    SOURCE_SYSTEM VARCHAR DEFAULT &#39;Teradata&#39;,<br>    TARGET_PLATFORM VARCHAR DEFAULT &#39;snowflake&#39;,<br>    ENTITY_TYPE VARCHAR DEFAULT &#39;Table&#39;,<br>    DDL_SOURCE_PATH VARCHAR,<br>    CREATED_AT TIMESTAMP_NTZ DEFAULT CURRENT_TIMESTAMP(),<br>    STATUS VARCHAR DEFAULT &#39;pending&#39;,<br>    COST_TIER VARCHAR,<br>    JIRA_TICKET VARCHAR,<br>    DETAILS VARCHAR<br>);<br><br>-- Step 2: Create a stored procedure for cost estimation<br>CREATE OR REPLACE PROCEDURE ESTIMATE_MIGRATION_COST(<br>    TABLE_NAME VARCHAR,<br>    NUM_COLUMNS INT,<br>    ESTIMATED_ROWS INT<br>)<br>RETURNS VARCHAR<br>LANGUAGE SQL<br>AS<br>BEGIN<br>  LET tier VARCHAR := &#39;&#39;;<br>  LET est_storage VARCHAR := &#39;&#39;;<br>  LET est_compute VARCHAR := &#39;&#39;;<br>  IF (:ESTIMATED_ROWS &lt; 10000) THEN<br>    tier := &#39;small&#39;;<br>    est_storage := &#39;$0.02&#39;;<br>    est_compute := &#39;$0.001&#39;;<br>  ELSEIF (:ESTIMATED_ROWS &lt;= 1000000) THEN<br>    tier := &#39;medium&#39;;<br>    est_storage := &#39;$0.50&#39;;<br>    est_compute := &#39;$0.003&#39;;<br>  ELSE<br>    tier := &#39;large&#39;;<br>    est_storage := &#39;$5.00&#39;;<br>    est_compute := &#39;$0.02&#39;;<br>  END IF;<br>  RETURN OBJECT_CONSTRUCT(<br>    &#39;table&#39;, :TABLE_NAME,<br>    &#39;tier&#39;, tier,<br>    &#39;est_storage_monthly&#39;, est_storage,<br>    &#39;est_compute_per_query&#39;, est_compute<br>  )::VARCHAR;<br>END;<br><br> -- Step 3: Create the MCP Server object (this is all it takes!)<br>CREATE OR REPLACE MCP SERVER AI_MCP_TEST.MCP_DEMO.PRODUCT_SUPPORT_MCP<br>FROM SPECIFICATION <br>$$<br>tools:<br>  - name: &quot;sql_write_tool&quot;<br>    type: &quot;SYSTEM_EXECUTE_SQL&quot;<br>    description: &quot;Execute read and write SQL queries on Snowflake.&quot;<br>    config:<br>      read_only: false<br>      warehouse: &quot;ADF_WH&quot;<br>  - name: &quot;sql-executor&quot;<br>    type: &quot;SYSTEM_EXECUTE_SQL&quot;<br>    description: &quot;Execute SQL queries for validation and schema exploration.&quot;<br>    config:<br>      warehouse: &quot;ADF_WH&quot;<br>  - name: &quot;estimate-migration-cost&quot;<br>    type: &quot;GENERIC&quot;<br>    identifier: &quot;AI_MCP_TEST.MCP_DEMO.ESTIMATE_MIGRATION_COST&quot;<br>    description: &quot;Estimate storage and compute costs for migrating a table to Snowflake.&quot;<br>    config:<br>      type: &quot;procedure&quot;<br>      warehouse: &quot;ADF_WH&quot;<br>    input_schema:<br>      type: &quot;object&quot;<br>      properties:<br>        TABLE_NAME:<br>          description: &quot;Name of the table being migrated&quot;<br>          type: &quot;string&quot;<br>        NUM_COLUMNS:<br>          description: &quot;Number of columns in the table&quot;<br>          type: &quot;number&quot;<br>        ESTIMATED_ROWS:<br>          description: &quot;Estimated number of rows&quot;<br>          type: &quot;number&quot;<br>$$;</pre><h4>Supported Managed MCP Tool Types</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*VGwmUKerIjsBJOyL35i6bg.png" /><figcaption>Figure 7: Snowflake Managed MCP and Supported tools( Image Credit Author)</figcaption></figure><h4>Snowflake Managed MCP URL Format</h4><p>When you create a Snowflake Managed MCP Server, you get an MCP URL in the format</p><pre>https://&lt;account_url&gt;/api/v2/databases/{db}/schemas/{schema}/mcp-servers/{name}</pre><p>No Docker. No Kubernetes. No server management. Just SQL.</p><h3>What does the actual DDL conversion look like?</h3><p>When the agent fetches a Teradata DDL from GitHub, it automatically applies conversion rules.</p><p><strong>Teradata DDL (source from GitHub)</strong></p><pre>CREATE MULTISET TABLE analytics_db.stg_web_logs, NO FALLBACK,<br>NO BEFORE JOURNAL, NO AFTER JOURNAL, CHECKSUM = DEFAULT<br>(<br>    LOG_ID INTEGER NOT NULL,<br>    SESSION_ID VARCHAR(100) CHARACTER SET LATIN NOT CASESPECIFIC,<br>    PAGE_URL VARCHAR(2000),<br>    EVENT_TYPE VARCHAR(50),<br>    EVENT_TS TIMESTAMP(6),<br>    USER_AGENT VARCHAR(500),<br>    IP_ADDRESS VARCHAR(45)<br>)<br>UNIQUE PRIMARY INDEX (LOG_ID);</pre><p><strong>Snowflake DDL (converted by the agent)</strong></p><pre>CREATE TABLE IF NOT EXISTS AI_MCP_TEST.PUBLIC.STG_WEB_LOGS (<br>    LOG_ID INTEGER NOT NULL,<br>    SESSION_ID VARCHAR(100),<br>    PAGE_URL VARCHAR(2000),<br>    EVENT_TYPE VARCHAR(50),<br>    EVENT_TS TIMESTAMP_NTZ(6),<br>    USER_AGENT VARCHAR(500),<br>    IP_ADDRESS VARCHAR(45)<br>);</pre><p><strong>What gets removed/changed?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*oXHSiREnEqHtdI_PfAfQNw.png" /><figcaption>Figure 7: Teradata-Snowflake feature mapping( Image Credit Author)</figcaption></figure><h4>But how does the agent know the correct data type mappings? Does it guess?</h4><p>No — it doesn’t guess. This is where <strong>Skills</strong> come in.</p><p><strong>What is a Skill?</strong></p><p>A Skill is a reusable knowledge file (.cortex/skills/&lt;name&gt;/SKILL.md) that the agent loads on-demand when it encounters a relevant task. Think of it like a reference manual that the agent opens when it needs specialized knowledge.</p><p>In this project, there’s a skill called teradata-to-snowflake-ddl that provides the <strong>authoritative</strong> data type mapping reference. The agent loads this skill automatically when it detects keywords like “teradata”, “ddl conversion”, or “type mapping.”</p><p>It lives at: <em>.</em><strong><em>cortex/skills/teradata-to-snowflake-ddl/SKILL.md</em></strong></p><h4>What’s inside the Skill?</h4><ol><li><strong>Complete Data Type Mapping Tables:</strong></li></ol><pre>BYTEINT → TINYINT<br>SMALLINT → SMALLINT<br>INTEGER → INTEGER<br>BIGINT → BIGINT<br>DECIMAL(p,s) → NUMBER(p,s)<br>FLOAT/REAL → FLOAT<br>CHAR(n) → CHAR(n) [strip CHARACTER SET]<br>VARCHAR(n) → VARCHAR(n) [strip CHARACTER SET, CASESPECIFIC]<br>LONG VARCHAR → VARCHAR(64000)<br>CLOB → VARCHAR(16777216)<br>BYTE(n) → BINARY(n)<br>VARBYTE(n) → VARBINARY(n)<br>BLOB → BINARY(8388608)<br>DATE → DATE [remove FORMAT]<br>TIME(p) → TIME(p)<br>TIMESTAMP(p) → TIMESTAMP_NTZ(p)<br>TIMESTAMP W/TZ → TIMESTAMP_TZ<br>INTERVAL * → VARCHAR(varies)<br>JSON → VARIANT<br>XML → VARIANT<br>PERIOD(*) → VARCHAR(varies) [or split into 2 cols]<br>ST_GEOMETRY → GEOMETRY</pre><p><strong>2. Clause Removal Rules:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*ePFakRYQLrj3Y-S0vHZ8_w.png" /></figure><p><strong>3. Transform Rules:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*0-_IYwuWPsS5z8zdhYwK5g.png" /><figcaption>Figure 8: Teradata-Snowflake transformation rules( Image Credit Author)</figcaption></figure><p><strong>4. Edge Cases &amp; Warnings</strong> (so the agent handles tricky scenarios):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*F19afo2XJnCLPIYGATuWIw.png" /><figcaption>Figure 9: Teradata-Snowflake edge cases — needs careful handling( Image Credit Author)</figcaption></figure><h4>Why does this matter?</h4><p>Without the skill, the AI would have to “remember” type mappings from its training data — which could be outdated or wrong. With the skill, a <strong>deterministic lookup table</strong> is loaded into context. Every conversion is consistent, correct, and auditable.</p><p>The skill also includes full conversion examples (simple tables, complex fact tables, volatile staging tables), so the agent has reference patterns to follow.</p><h4>What about the audit trail?</h4><p>Every migration gets logged into the <strong>MIGRATION_LOG</strong> Table — so <em>Amy</em> (the PM) always knows what happened.</p><p><strong>On success</strong>, the agent logs:</p><pre>INSERT INTO AI_MCP_TEST.MCP_DEMO.MIGRATION_LOG<br>(ENTITY_NAME, SOURCE_SYSTEM, TARGET_PLATFORM, ENTITY_TYPE,<br>DDL_SOURCE_PATH, STATUS, COST_TIER, JIRA_TICKET)<br>VALUES<br>(&#39;STG_WEB_LOGS&#39;, &#39;Teradata&#39;, &#39;snowflake&#39;, &#39;Table&#39;,<br>&#39;ddl/analytics_db.stg_web_logs.sql&#39;, &#39;completed&#39;, &#39;medium&#39;, &#39;MIG-142&#39;);</pre><p><strong>On failure</strong> (DDL not found, or SQL error):</p><pre>INSERT INTO AI_MCP_TEST.MCP_DEMO.MIGRATION_LOG<br>(ENTITY_NAME, SOURCE_SYSTEM, TARGET_PLATFORM, ENTITY_TYPE,<br>DDL_SOURCE_PATH, STATUS, JIRA_TICKET, DETAILS)<br>VALUES<br>(&#39;FACT_ORDERS&#39;, &#39;Teradata&#39;, &#39;snowflake&#39;, &#39;Table&#39;,<br>&#39;ddl/warehouse_db.fact_orders.sql&#39;, &#39;in-complete&#39;, &#39;MIG-138&#39;,<br>&#39;DDL file not found in GitHub&#39;);</pre><p><strong>Conditional Ticket Resolution</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*Lfs--JC11XBQ0ckGWmstVA.png" /><figcaption>Figure 10: <strong>Conditional Ticket Resolution </strong>( Image Credit Author)</figcaption></figure><h4>Can you show me the whole thing running?</h4><p>Here’s what the developer sees in their terminal:</p><pre>User: Run the migration pipeline for pending tickets<br>Cortex: I&#39;ll run the migration operations pipeline. Let me start by checking<br>for pending migration tasks in Jira.<br>[Calling: get_jira_pending_tasks]<br>Found ticket MIG-142: &quot;Migrate stg_web_logs from Teradata&quot;<br>Tables to migrate: analytics_db.stg_web_logs<br>Transitioning MIG-142 to &quot;In Progress&quot;…<br>[Calling: transition_jira_task → In Progress]<br>✓ Ticket updated.<br>Fetching Teradata DDL from GitHub…<br>[Calling: get_github_file_content → ddl/analytics_db.stg_web_logs.sql]<br>Got the source DDL. Converting to Snowflake format:<br>- Removed MULTISET, NO FALLBACK, JOURNAL settings<br>- Removed CHARACTER SET LATIN NOT CASESPECIFIC<br>- Removed UNIQUE PRIMARY INDEX<br>- Added IF NOT EXISTS, retargeted to AI_MCP_TEST.PUBLIC<br>Creating table in Snowflake…<br>[Calling: sql_write_tool → CREATE TABLE IF NOT EXISTS …]<br>✓ Table created successfully.<br>Validating structure…<br>[Calling: sql-executor → INFORMATION_SCHEMA query]<br>✓ 7 columns confirmed, types match expected conversion.<br>Estimating migration cost…<br>[Calling: estimate-migration-cost → 7 cols, 500K rows]<br>→ Tier: Medium | Storage: $0.50/mo | Compute: $0.003/query<br>Attaching converted DDL to Jira…<br>[Calling: add_jira_attachment → snowflake_ddl_2025–06–30.sql]<br>✓ DDL attached.<br>Attaching migration report to Jira…<br>[Calling: add_jira_attachment → migration_report_2025–06–30.md]<br>✓ Report attached.<br>Closing ticket…<br>[Calling: complete_jira_task → MIG-142]<br>✓ MIG-142 transitioned to Done.<br>Migration complete for MIG-142:<br>┌─────────────────────────────────────────────┐<br>│ Table: STG_WEB_LOGS │<br>│ Status: ✓ Migrated │<br>│ Tier: Medium ($0.50/mo) │<br>│ Ticket: MIG-142 → Done │<br>└─────────────────────────────────────────────┘</pre><p><strong>One command. Nine steps. Zero manual context-switching.</strong></p><p><strong>Before vs. After</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*BWAJf6B-yBlu2DG7HPfYxg.png" /><figcaption>Figure 11: Implementation with and without MCP( Image Credit Author)</figcaption></figure><h3>Solution Architecture</h3><p>Here is the end-to-end architecture we build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*t5o9_VbfhRsHjUnCKtEbAQ.png" /><figcaption>Figure 12: Solution Architecture using MCP( Image Credit Author)</figcaption></figure><h4>What should I keep in mind when building my own MCP setup?</h4><p>Here’s a best practices checklist from production experience:</p><h4>Architectural &amp; Tool Design</h4><ul><li><strong>Design for Intent, Not Raw Operations</strong> — Name tools get_pending_migration_tasks, not execute_jql_query</li><li><strong>Single Responsibility Principle</strong> — One tool = one job. Don’t combine “fetch + convert + create” into one tool.</li><li><strong>Enforce Context Minimalism</strong> — Return only what the AI needs. Don’t dump entire API responses.</li><li><strong>Prefer Stateless, Idempotent Actions</strong> — CREATE TABLE IF NOT EXISTS (safe to re-run) over CREATE TABLE (fails on second run)</li></ul><h4>Security &amp; Governance</h4><ul><li><strong>Use only trusted MCP servers</strong> — Tool descriptions can be an attack surface (prompt injection)</li><li><strong>Apply Strict Least Privilege</strong> — Read-only tools separate from write tools</li><li><strong>Validate every parameter server-side</strong> — Never trust the AI’s input without checking</li><li><strong>Introduce an MCP Gateway</strong> — For production, put a control plane in front of your MCP servers</li></ul><h4>Schema &amp; Interface Design</h4><ul><li><strong>Flatten arguments</strong> — Avoid deeply nested JSON inputs. Keep it simple for the AI.</li><li><strong>Mandate pagination</strong> — Don’t return 10,000 rows. Cap results with max_results.</li><li><strong>Provide corrective error responses</strong> — Don’t just say “error.” Say what went wrong and how to fix it.</li></ul><h4>Testing &amp; Debugging</h4><ul><li><strong>Use the MCP Inspector</strong> — A developer tool for testing MCP servers interactively before connecting them to AI</li><li><strong>Test tools in isolation</strong> — Each tool should work perfectly before wiring it into a workflow</li></ul><h4>Where do I start?</h4><p><strong>1.</strong> <strong>Build one Custom MCP Server</strong> — Pick a system you use daily (Jira, Slack, your internal API). Expose 2–3 tools using FastMCP. Run it locally.</p><pre>pip install fastmcp requests<br>python mcp/jira_mcp_server.py<br>cortex mcp add jira-mcp http://localhost:8000/mcp - transport http</pre><p>2. <strong>Create one Managed MCP Server in Snowflake</strong> — Wrap an existing stored procedure or query as a GENERIC tool. Zero infrastructure.</p><pre>CREATE MCP SERVER my_first_mcp FROM SPECIFICATION $$<br>tools:<br>  - name: &quot;my-tool&quot;<br>    type: &quot;GENERIC&quot;<br>    identifier: &quot;MY_DB.MY_SCHEMA.MY_PROCEDURE&quot;<br>    description: &quot;What this tool does in plain English&quot;<br>$$;</pre><p><strong>3. Write your AGENTS.md</strong> — Define a step-by-step workflow. Be explicit about:</p><ul><li>What tools to call</li><li>In what order</li><li>What to do when things fail</li><li>What to report when done</li></ul><h4>Conclusion</h4><p>MCP isn’t just another protocol. It’s the infrastructure layer that turns AI models from “smart chatbots” into “autonomous workers” that operate across your real business systems.</p><h4>Key takeaways:</h4><ul><li><strong>MCP solves the integration problem</strong> — One standard replaces dozens of custom connectors</li><li><strong>Snowflake Managed MCP Servers eliminate infrastructure</strong> — Define tools in SQL; Snowflake handles the rest</li><li><strong>Custom MCP Servers give you full control</strong> — Connect any external system with a few lines of Python</li><li><strong>AGENTS.md provides determinism</strong> — Your AI follows a recipe, not its imagination</li><li><strong>Audit logging closes the governance loop</strong> — Every action is tracked; every migration is auditable</li></ul><p>The Teradata-to-Snowflake migration pipeline is just one example. The same pattern applies to any multi-system workflow: data quality checks, onboarding automation, incident response, report generation — anywhere humans currently context-switch between tools.</p><p>One command. One agent. All your systems. Connected.</p><p><strong>Now, You Know What To Do!</strong></p><ul><li><strong>Please share</strong> this with anyone who you think will be interested. It might help them, and it really helps me!</li><li>Please <strong>give me 50 claps</strong>! (Just hold down the clap button.)</li><li>Feel free to <strong>leave a comment</strong> 💬.</li><li>🙏 If you found this article helpful, <strong>subscribe and hit it</strong>. <a href="https://medium.com/@singh.sanjiv"><strong><em>Follow</em></strong></a><strong> </strong>— it helps more people discover it.</li><li>🌱 Good ideas tend to spread. I truly appreciate it when readers pass them along.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e044e839f865" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a High-Scale Distributed Multitenant Task Scheduler]]></title>
            <link>https://medium.com/@singh.sanjiv/building-a-high-scale-distributed-multitenant-task-scheduler-821b147a2005?source=rss-30311cf4ee3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/821b147a2005</guid>
            <category><![CDATA[task-scheduling]]></category>
            <category><![CDATA[scheduling]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Sanjiv Singh]]></dc:creator>
            <pubDate>Tue, 21 Apr 2026 16:31:16 GMT</pubDate>
            <atom:updated>2026-04-22T10:25:55.067Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. The Core Problem</h3><p>How do you build a platform that executes millions of tasks at precise times for thousands of different customers (tenants) without them interfering with each other?</p><p>A task scheduler at scale isn’t just a “timer.” It is a complex coordination problem involving <strong>isolation</strong> (don’t let Tenant A’s 1M emails slow down Tenant B’s 1 payment), <strong>precision</strong> (run exactly at 10:00:00), and <strong>availability</strong> (no single point of failure).</p><h3>2. Assumptions</h3><p>I assume you understand the basics of Relational Databases (MySQL), Message Queues, and the concept of “Sharding” (splitting data across multiple databases).</p><h3>3. Requirements</h3><p><strong>Functional Requirements:</strong></p><ul><li>Schedule tasks for a precise UTC time.</li><li>Multiple tenants (“shards”) coexist on the same infrastructure.</li><li>Support multiple priority levels (e.g., Critical, High, Normal).</li></ul><p><strong>Non-Functional Requirements :</strong></p><ul><li><strong>Tenant Isolation:</strong> No “loud neighbor” can starve other tenants of resources.</li><li><strong>Prioritization:</strong> A critical task must always run before a low-priority one.</li><li><strong>Precision:</strong> If a task is due at 10:00:01, it must not execute at 10:00:10.</li><li><strong>Dynamic Scalability:</strong> The system must automatically provision new processing capacity when a tenant’s load spikes.</li></ul><h3>4. Scale</h3><ul><li><strong>1 Million+</strong> scheduled tasks per minute across the platform.</li><li><strong>Shard-Aware Scaling:</strong> Each MySQL shard can manage 10,000+ tenants, demanding massive parallelism.</li><li><strong>1,000+</strong> dedicated executor nodes that need dynamic lifecycle management.</li></ul><h3>5. Evolution of the Design</h3><h4>Initial Design</h4><p>Let’s make a basic design.</p><blockquote>User creates task → saved into MySQL table → TaskExecutor pull peding task from table and executes it.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N4vDxNKlsQLhSKIw6eJLFg.png" /><figcaption>Initial Design (Image Credit -Author)</figcaption></figure><p>This is very simple and intuitive, but it has many gaps in requirements. In a set of steps, we will evolve around this design.</p><h4>Step 1: The Initial Design &amp; The Multi-Tenant Problem</h4><p><strong>The Bottleneck:</strong> How do we store millions of tasks for thousands of customers without one big table becoming a performance nightmare?</p><ul><li><strong>Initial Design:</strong> One big Tasks table with a tenant_id column.</li><li><strong>The Evolution:</strong> To handle <strong>Multi-tenancy</strong>, we use <strong>Sharded MySQL</strong>.</li><li><strong>Why choose this?</strong> By sharding by <strong>tenant_id.</strong></li><li>We ensure that Tenant A&#39;s data resides on Shard 1, while Tenant B&#39;s data resides on Shard 2. This prevents a &quot;noisy neighbor&quot; from locking up the database for everyone else.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bu3aGWcWHGOb2HvmjfQgqA.png" /><figcaption>Tenant database shards (Image credit — Author)</figcaption></figure><h4>Step 2: Handling Scheduled Tasks (Cron Materializer)</h4><p><strong>The Bottleneck:</strong> If we have 100 million tasks scheduled for the future, we can’t poll the “Scheduled” table every second. It’s too slow.</p><ul><li><strong>The Design:</strong> We introduce the <strong>Cron Materializer</strong>.</li><li><strong>How it works:</strong> This service runs every minute. It looks at the “Scheduled Task” table and identifies everything due in the <em>next</em> 60 seconds. It “materializes” (moves) these into a high-speed <strong>Executable Task</strong> table.</li><li><strong>Why choose this?</strong> It decouples the “Long-term storage” from the “Immediate execution” path. The execution engine only ever looks at a tiny, hot table of tasks due <em>now</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXzuqCTEat5vPnwJ49usrQ.png" /><figcaption>Schedule task handkling through Cron Scheduler (Image credit — Author)</figcaption></figure><h4>Step 3: Scaling by Decoupling Pullers and Executors</h4><p><strong>The Bottleneck:</strong> If one component fetches tasks and executes them, a slow execution (like a timed-out API call) will block the system from fetching the next task.</p><ul><li><strong>The Design:</strong> We split the labor into <strong>Task Pullers</strong> and <strong>Task Executors</strong>.</li><li><strong>How it works:</strong> 1. <strong>Pullers:</strong> Their only job is to grab tasks from the “Executable” table and put them into a queue. 2. <strong>Executors:</strong> Their only job is to listen to that queue and do the actual work.</li><li><strong>Why choose this?</strong> This allows us to scale them independently. If we have a lot of small tasks, we add more Pullers. If we have very “heavy” tasks that take a long time to run, we add more Executors.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OvnZWCdpnpXAxvWODAFwgw.png" /><figcaption>Decoupling Task Pullers and Task Executors(Image credit — Author)</figcaption></figure><h4>Step 4: Handling Task Priorities</h4><p><strong>The Bottleneck:</strong> A “Normal” priority task (sending a newsletter) shouldn’t delay a “Critical” priority task (processing a password reset).</p><ul><li><strong>The Design:</strong> <strong>Multi-Lane Priority Queues (P1, P2, P3).</strong></li><li><strong>How it works:</strong> Pullers sort tasks into different queues based on priority. Executors are configured to prioritize the P1 queue. They only look at P2 if P1 is empty.</li><li><strong>Why choose this?</strong> It guarantees that high-importance tasks “jump the line,” ensuring <strong>on-time execution</strong> for critical business logic.</li></ul><h4>Step 5: Scheduler Orchestrator</h4><p><strong>The Bottleneck:</strong> How do we know <em>how many Pullers for a specific tenant</em> or <em>Executors to run for a specific priority</em>?</p><ul><li><strong>The Design:</strong> <strong>Scheduler Orchestrator + Apache Zookeeper.</strong></li><li><strong>How it works:</strong> 1. <strong>Zookeeper</strong> acts as the “Source of Truth” for which workers are alive (using Ephemeral Nodes). 2. The <strong>Orchestrator</strong> monitors the system. If it sees Tenant 1 has a huge spike in tasks, it <strong>dynamically provisions</strong> more “Tenant 1 Pullers” and registers them in Zookeeper.</li><li><strong>Why choose this?</strong> It makes the system “Elastic.” We don’t waste money running 1000 workers all the time; we only spin them up when the load demands it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_wWj2ut6kEWoBaqRv8stSg.png" /><figcaption>Schedule Orchestator monitors and manges through Zookeeper (Image credit — Author)</figcaption></figure><h4>Step 6: Monitoring and Logging</h4><p><strong>The Bottleneck:</strong> How do we know if a task failed or if we are missing our execution deadlines?</p><ul><li><strong>The Design:</strong> <strong>Logging Queue + Telemetry Service.</strong></li><li><strong>How it works:</strong> Every time an Executor finishes a task (Success or Failure), it pushes a small event to a <strong>Logging Queue</strong>. An analysis service reads this to track “Delayed Task Execution” or “Failed Task Count.”</li></ul><h3>6. The Final Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_sf5rpbDe_Z1DoR4vPVPA.png" /><figcaption>Final Architecture (Image credit -Author)</figcaption></figure><p>The final architecture is a highly decoupled, elastic system:</p><ol><li><strong>Ingestion:</strong> Tasks are sharded into MySQL to ensure no single database is a bottleneck.</li><li><strong>Preparation:</strong> Cron Materializers promote tasks from “Scheduled” to “Executable” every minute.</li><li><strong>Distribution:</strong> Tenant-specific <strong>Pullers</strong> move tasks into <strong>Priority-specific Queues</strong>.</li><li><strong>Execution:</strong> <strong>Executors</strong> pick tasks based on priority (P1 &gt; P2 &gt; P3) and execute them.</li><li><strong>Governance:</strong> <strong>Zookeeper and the Orchestrator</strong> manage the fleet of workers, spinning them up or down based on the actual number of tasks per tenant.</li><li><strong>Visibility:</strong> All actions are logged to an async queue for real-time monitoring of performance and failures.</li></ol><h3>7. Implementation</h3><blockquote><strong>To help you see this in action, I’ve built an end-to-end version of this architecture that you can spin up right now on your local machine.</strong></blockquote><p>End-to-end working solution <a href="https://github.com/sanjivsingh/distributed_transactions/tree/master/distributed_multitenant_task_scheduler"><strong>Source code</strong></a>, and step-by-step guide to deploy locally.</p><ul><li>Task Service: <a href="https://github.com/sanjivsingh/distributed_transactions/blob/master/distributed_multitenant_task_scheduler/app.py">app.py</a></li><li>Scheduler Orchestrator: <a href="https://github.com/sanjivsingh/distributed_transactions/blob/master/distributed_multitenant_task_scheduler/orchestrator.py">orchestrator.py</a></li><li>Cron Materialiser: <a href="https://github.com/sanjivsingh/distributed_transactions/blob/master/distributed_multitenant_task_scheduler/schedule_materialiser.py">schedule_materialiser.py</a></li><li>Shard Manager: <a href="https://github.com/sanjivsingh/distributed_transactions/blob/master/distributed_multitenant_task_scheduler/shard_manager.py">shard_manager.py</a></li><li>Task Executor: <a href="https://github.com/sanjivsingh/distributed_transactions/blob/master/distributed_multitenant_task_scheduler/task_executor.py">task_executor.py</a></li><li>Task Pullar: <a href="https://github.com/sanjivsingh/distributed_transactions/blob/master/distributed_multitenant_task_scheduler/task_puller.py">task_puller.py</a></li></ul><h3>8. Conclusion</h3><p>A distributed task scheduler isn’t just about timers. A production-grade system must actively manage <strong>tenancy</strong> and <strong>priority</strong> from ingestion to execution. By decoupling the schedule timer (Zookeeper) from the persistent task payload (MySQL), and managing the worker fleet’s topology with Zookeeper, we create a system that can not only handle 1,000+ tenants on a single platform but also guarantee that Tenant B’s critical payment will never be stuck behind Tenant A’s bulk emails.</p><p>See you next time!</p><p><strong>You Know What To Do!</strong></p><ul><li><strong>Please share</strong> this with anyone that you think will be interested. It might help them, and it really helps me!</li><li>Please <strong>give me 50 claps</strong>! (Just hold down the clap button.)</li><li>Feel free to <strong>leave a comment</strong> 💬.</li><li>🙏 If you found this article helpful, <strong>subscribe and </strong>give it a hit. <a href="https://medium.com/@singh.sanjiv"><strong><em>Follow</em></strong></a><strong> </strong>— it helps more people discover it.</li><li>🌱 Good ideas tend to spread. I truly appreciate it when readers pass them along.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=821b147a2005" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Robinhood-Scale Brokerage System]]></title>
            <link>https://medium.com/@singh.sanjiv/designing-a-robinhood-scale-brokerage-system-8eeb330ae4f6?source=rss-30311cf4ee3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8eeb330ae4f6</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Sanjiv Singh]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 10:10:24 GMT</pubDate>
            <atom:updated>2026-04-08T10:10:24.882Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Core Problem</h3><p>How do you build a platform where millions of people can buy and sell stocks in milliseconds without losing a single cent or showing an outdated price? A brokerage isn’t just a website; it’s a high-integrity bridge between a fast-moving stock exchange and a user’s bank account.</p><h3>Assumptions</h3><p>We are assuming you know the basics of how a stock market works (buyers, sellers, and prices). We also assume there is an external <strong>Stock Exchange</strong> (like NASDAQ) that we talk to via an API to actually execute the trades.</p><h3>Requirements</h3><h4>Functional Requirements</h4><ul><li><strong>Real-time Prices:</strong> Users must see stock prices as they happen.</li><li><strong>Trading:</strong> Users can place “Market” orders (buy now at any price) and “Limit” orders (buy only if the price hits $X).</li><li><strong>Portfolio:</strong> Users need to see their cash balance and the value of stocks they own.</li></ul><h4>Non-Functional Requirements (The Real Pain Points)</h4><ul><li><strong>Atomic Consistency:</strong> You cannot let a user spend money they don’t have.</li><li><strong>Ultra-Low Latency:</strong> A price delay of 1 second can cost a user money.</li><li><strong>High Availability:</strong> If the app goes down during a market crash, it’s a disaster.</li></ul><h3>The Scale</h3><ul><li><strong>20 Million Users</strong> (DAU).</li><li><strong>5 Million Trades</strong> per day.</li><li><strong>Traffic Spikes:</strong> 10x normal volume during the “Opening Bell” (9:30 AM).</li></ul><blockquote>This design is based on my own understanding of systems design and experience. It may or may not be the same as the real Robinhood system.</blockquote><h3>Initial Design:</h3><p>In a simple world, the user’s app talks to a server, which talks to a Database and the Exchange.</p><p><strong>The Bottleneck:</strong> If 20 million people ask the Database “What is the price of Apple?” every second, the Database will melt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHVYGLIjpvgki2tdPOJIZw.png" /><figcaption>Initial System Design (Image credit — author)</figcaption></figure><h3>Step-by-Step Evolution</h3><h4>Step 1: The Price Feed</h4><p><strong>The Question:</strong> How do we send live prices to 20M users without exploding our bandwidth?</p><ul><li><strong>Solution 1(Polling):</strong> App asks “What’s the price?” every second. This is Too slow and heavy.</li><li><strong>Solution 2(WebSockets): (recommended)</strong>A persistent pipe. <em>We push updates only when they change.</em></li><li><strong>Optimization:</strong> We use <strong>Redis Pub/Sub</strong>. The Exchange-Service pushes a price to a Redis “Channel,” and the WebSocket servers broadcast it to everyone watching that stock.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SO5QvrBCsk1xSN9KFOYxzQ.png" /><figcaption>System Design — How Stock Price change reaches to user in real time(Image credit — author)</figcaption></figure><h4>Step 2: The “Double Spend” (Consistency Problem)</h4><p><strong>The Question:</strong> How do we stop a user with $100 from buying $500 worth of stock?</p><ul><li><strong>Solution 1 :(Kafka First):</strong> Send the order to a queue and check the balance later. This could be Dangerous. The user might overdraw before the queue is processed.</li><li><strong>Solution 2(Atomic DB Check):</strong> (<strong>recommended</strong>)Use a SQL transaction to “reserve” money before sending the order to the exchange.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPYN_G-yRcDlTBIY80c-kw.png" /><figcaption>Flow -avoiding double spending(Image credit — author)</figcaption></figure><h4>Step 3: The “Limit Order” (Thundering Herd Problem)</h4><p><strong>The Question:</strong> If 1 million people want to buy at $150, and the price hits $150, how do we find them all instantly?</p><ul><li><strong>Solution 1(SQL Search):</strong> SELECT * WHERE price = 150. <strong>Verdict:</strong> Way too slow for 1M rows.</li><li><strong>Solution 2 (Redis Sorted Sets):</strong> (<strong>recommended</strong>) Store orders in a <strong>Sorted Set</strong> where the “Score” is the price. We can find a “Range” of prices in <strong>O(log N)</strong> time.</li></ul><h3>Low-Level Design:</h3><h3>Users API Call End-to-End Flow</h3><ul><li><strong>GET </strong><strong>/v1/portfolio</strong>: Returns cash and stock list.</li><li><strong>POST </strong><strong>/v1/orders/ticket</strong>: Generates a temporary ID to prevent double-clicking (Idempotency).</li><li><strong>POST </strong><strong>/v1/orders</strong>: <strong>Payload:</strong> {ticket_id: &quot;xyz&quot;, symbol: &quot;AAPL&quot;, qty: 1, type: &quot;MARKET&quot;}</li></ul><p><strong>Flow:</strong></p><ul><li>Service checks ticket_id in Redis (to avoid duplicates).</li><li>Service runs SQL: UPDATE accounts SET balance = balance - 150 WHERE user_id = 1 AND balance &gt;= 150.</li><li>If SQL succeeds, it sends the trade to the Exchange.</li></ul><h3>Portfolio Aggregation</h3><p>To show a user their total value (50 stocks), we don’t want 50 Redis calls. We use a <strong>Lua Script</strong> to fetch everything in one go.</p><p>Lua</p><pre>-- Redis Lua Script for Portfolio Valuation<br>local total_value = 0<br>local user_stocks = redis.call(&#39;HGETALL&#39;, KEYS[1]) -- User&#39;s holdings<br>for i=1, #user_stocks, 2 do<br>    local symbol = user_stocks[i]<br>    local quantity = tonumber(user_stocks[i+1])<br>    local price = tonumber(redis.call(&#39;GET&#39;, &#39;price:&#39; .. symbol))<br>    total_value = total_value + (quantity * price)<br>end<br>return total_value</pre><h3>The Limit Order Worker</h3><p>To handle the “Thundering Herd,” we use Redis to index prices. When the price of AAPL moves from $150.05 to $150.00, we need to trigger every order between those two numbers.</p><p><strong>Logic (Pseudo-code):</strong></p><pre># When price hits 150.00<br># We look for all buy orders between 150.00 and 150.05<br>triggered_orders = redis.zrangebyscore(&quot;orders:AAPL&quot;, 150.00, 150.05)<br>for order_id in triggered_orders:<br>    kafka.publish(&quot;execute_trade&quot;, order_id)<br>    redis.zrem(&quot;orders:AAPL&quot;, order_id)</pre><h4>Stock Price Monitor Service (The Stock price change -&gt; Trigger limit order Engine)</h4><p><strong>The Bottleneck:</strong> When a stock price moves (e.g., Apple drops from <strong>$150.05</strong> to <strong>$150.00</strong>), thousands of users might have “Limit Buy” orders set at $150.00, $150.01, or $150.03. If you simply query a SQL database for these orders, the database will choke under the pressure of the search.</p><p><strong>The Solution: </strong>Instead of searching a database, we keep the active limit orders in a <strong>Redis Sorted Set (</strong><strong>ZSET)</strong>.</p><ol><li><strong>Structure:</strong> For every stock, we create a ZSET called orders:AAPL.</li><li><strong>Score:</strong> The “Score” in the ZSET is the <strong>Price</strong>.</li><li><strong>Member:</strong> The “Member” is the order_id.</li></ol><h4>How the Trigger Works:</h4><ol><li><strong>Price Drop:</strong> The Exchange sends an update: <strong>AAPL is now $150.00.</strong></li><li><strong>Range Query:</strong> The Monitor Service doesn’t just ask for $150.00. It asks Redis: <em>“Give me all orders where the price is between the </em><strong><em>old price</em></strong><em> ($150.05) and the </em><strong><em>new price</em></strong><em> ($150.00).”</em></li><li><strong>Efficiency:</strong> This is a ZRANGEBYSCORE operation in Redis, which is O(log N + M). It is incredibly fast.</li><li><strong>Execution:</strong> The IDs of the triggered orders are pushed into <strong>Kafka</strong>, where workers pick them up to execute them against the Exchange.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J7BBtbAwXEEbFM21Dc1g2A.png" /><figcaption>Flow — how Stock price change efficiently triggers limit orders in price range(Image credit — author)</figcaption></figure><h4>Final Design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2lz0bDEXxCj3VtzBHnc9_Q.png" /><figcaption>Final System Design (Image credit — author)</figcaption></figure><h4><strong>Scaling System</strong></h4><ul><li><strong>Database Sharding (Horizontal Scaling)</strong> Even the fastest PostgreSQL server can’t handle 5 million trades and 20 million portfolio lookups daily on its own. <strong>We shard the database by </strong><strong>user_id.</strong></li><li><strong>WebSocket Partitioning (The Fan-Out Problem)</strong> One server can only handle about 65,000 open connections. To support 20 million users, you need a massive fleet of WebSocket servers. <strong>We use a Load Balancer to distribute users across thousands of WebSocket nodes.</strong></li><li><strong>Regional Deployments (Edge Scaling) </strong>If your servers are in Virginia but your user is in Tokyo, the time it takes for light to travel across the ocean adds 200ms of lag. In trading, that’s an eternity. <strong>We deploy “Read-Only” replicas of the Price Feed in different geographic regions (US-East, US-West, Europe, Asia).</strong></li><li><strong>Scaling the Matching Engine (Limit Orders)</strong> Since we have 20 million users, the Redis ZSET for a hot stock like “AAPL” might still get very large. <strong>We shard the Limit Order Monitor by Stock Symbol.</strong> One worker handles “A through M,” and another handles “N through Z.” This ensures that a “Thundering Herd” on Apple doesn’t slow down someone trying to trade Zoom.</li></ul><h3>Conclusion</h3><p>Building a brokerage is a battle between <strong>speed</strong> and <strong>safety</strong>. We use <strong>WebSockets and Redis</strong> for the speed of price updates, but we fall back to <strong>ACID-compliant SQL transactions</strong> for the safety of the user’s money. By using <strong>Sorted Sets</strong> for limit orders, we ensure that even when the market goes crazy, our system stays standing.</p><p>See you next time!</p><p><strong>You Know What To Do!</strong></p><ul><li><strong>Please share</strong> this with anyone that you think will be interested. It might help them, and it really helps me!</li><li>Please <strong>give me 50 claps</strong>! (Just hold down the clap button.)</li><li>Feel free to <strong>leave a comment</strong> 💬.</li><li>🙏 If you found this article helpful, <strong>subscribe and </strong>give it hit <a href="https://medium.com/@singh.sanjiv"><strong><em>Follow</em></strong></a><strong> </strong>— it helps more people discover it.</li><li>🌱 Good ideas tend to spread. I truly appreciate it when readers pass them along.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8eeb330ae4f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data sourcing and QA/Validation at Scale like Deluxe/Acxiom/Epsilon:]]></title>
            <link>https://medium.com/@singh.sanjiv/data-sourcing-and-qa-validation-at-scale-like-deluxe-acxiom-epsilon-7ec2018baecc?source=rss-30311cf4ee3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ec2018baecc</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-quality]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[aws-glue-crawler]]></category>
            <dc:creator><![CDATA[Sanjiv Singh]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 21:40:11 GMT</pubDate>
            <atom:updated>2026-04-08T10:15:52.430Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you are expecting a grocery delivery. Instead of a few bags, 45 massive trucks show up and dump <strong>300 million items</strong> on your driveway. Each item has <strong>1,000 different labels</strong> (price, weight, expiry, etc.) that you need to check.</p><p>How do you make sure nothing is “rotten” (nulls), “fake” (wrong data types), or “missing” (empty files) without spending a fortune or waiting weeks to finish? At Deluxe/<a href="https://www.acxiom.com/data-monetization/">Acxiom</a>/<a href="https://www.epsilon.com/us">Epsilon</a>/other data sourcing and monetizing corporation, they face this daily: <strong>How do they validate massive data at scale before it ruins our marketing insights?</strong></p><blockquote><strong><em>Note:</em></strong><em> This design is based on my own understanding of systems design and professional experience. It is a conceptual architectural exercise and may or may not reflect the actual internal systems used by </em>Deluxe/<a href="https://www.acxiom.com/data-monetization/">Acxiom</a>/<a href="https://www.epsilon.com/us">Epsilon</a><em>.</em></blockquote><h4>Assumptions</h4><p>We assume you know your way around <strong>S3 buckets</strong>, have heard of <strong>Spark</strong> (the engine that moves big data), and understand that “Bad Data In = Bad Data Out.”</p><h4>Requirements</h4><p><strong>Functional</strong></p><ul><li><strong>Schema Check</strong>: Does the file have all 1,000 columns?</li><li><strong>Data Integrity</strong>: Are “must-have” fields (like Address) actually there?</li><li><strong>Format Validation</strong>: Can we actually read the file (CSV vs GZIP)?</li></ul><p><strong>Non-Functional</strong></p><ul><li><strong>Scale</strong>: Handle 300 million rows today, and 300 billion in history.</li><li><strong>Cost-Efficiency</strong>: Don’t spin up a $100/hour cluster just to find out a file is empty.</li><li><strong>Speed</strong>: Catch errors in minutes, not hours.</li></ul><blockquote><strong><em>The Real Pain Point:</em></strong><em> Most companies wait until the </em>end<em> of the process to find errors. We need to </em><strong><em>Fail-Fast</em></strong><em> to save time and money.</em></blockquote><h4>The Scale</h4><ul><li><strong>Daily Volume</strong>: 300 Million Rows (approx. 500 GB).</li><li><strong>Width</strong>: 1,000 to 2,500 Columns.</li><li><strong>Total History</strong>: 300 Billion Records.</li><li><strong>Input</strong>: 2,500+ files from 45 different vendors.</li></ul><h3>Initial Design:</h3><p><strong>Question on Design?</strong> Why not just point Spark at the S3 bucket and hit “Go”?</p><p><strong>The Problem:</strong> This is the “fingers crossed” approach. What if the vendor sent <strong>zero-byte files</strong>? Or what if only 10 out of 45 trucks showed up? <strong>Comparison:</strong> Spark takes 5–10 minutes just to “warm up.” If you run it on empty or missing data, you’ve wasted expensive cluster time to get an error message you could have seen in a second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QqQxg8Wkc_KpUY1Uo-IUw.png" /><figcaption>Step 1: Initial System design(Image Credit : Author)</figcaption></figure><h3>Step-by-Step Evolution for Final Design</h3><h4>Step 1: Lambda Sanity</h4><p><strong>Question on Design?</strong> How do we stop the “empty file” problem without starting Spark?</p><p><strong>Solution:</strong> We use an <strong>S3 Trigger</strong> to wake up a tiny <strong>Lambda</strong>. It acts like a bouncer at a club — checking IDs (file size and metadata) before letting anyone in. <strong>Comparison (Lambda vs. Spark):</strong> Lambda is nearly free and starts instantly. It checks the “Sanity” of the data. If the truck is empty, Lambda stops the show before the $100/hour Spark cluster even moves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxC4pGdTR_NKNo2NlX3Ysg.png" /><figcaption>Step 1: Lambda Sanity System design(Image Credit : Author)</figcaption></figure><h4>Step 2: Crawler &amp; Schema Evolution</h4><p><strong>Question on Design?</strong> How do we handle new columns without scanning all 300 billion rows every time?</p><p><strong>The Problem:</strong> We don’t want to accidentally delete a column just because today’s vendor file had a typo.</p><p><strong>Solution:</strong> Enter the <strong>AWS Glue Crawler</strong>. It maps the data into a <strong>Glue Data Catalog</strong>. We configure it for <strong>Incremental Loads</strong> (only looking at new folders) and set it to <strong>“Add new columns only”</strong> to protect our history. <strong>Comparison:</strong> Manual schema management vs. Crawler. The Crawler automates the “Discovery” so Spark knows exactly what the 1,000 columns look like before it starts reading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiZnU2chSHZGurKzlg0txg.png" /><figcaption>Step 2: Crawler &amp; Schema Evolution System design(Image Credit : Author)</figcaption></figure><h4><strong>Step 3: Glue Data Quality</strong></h4><p><strong>Question on Design?</strong> How do we check 10,000 rules on 500GB of data without scanning the file 10,000 times?</p><p><strong>The Scale Problem:</strong> 1,000 columns * 10 rules = <strong>10,000 checks</strong>. If you use <strong>Athena SQL</strong> or <strong>Standard Spark code</strong>, you might end up scanning the data over and over, which is slow and expensive.</p><p><strong>Solution:</strong> <strong>AWS Glue Data Quality (DQDL)</strong>. <strong>Comparison (Glue DQ vs. Spark vs. Athena):</strong></p><ul><li><strong>Athena:</strong> Great for one-off questions, but writing 10,000 SQL statements is a nightmare.</li><li><strong>Custom Spark:</strong> Powerful, but you have to write thousands of lines of if/else logic.</li><li><strong>Glue DQ:</strong> Uses <strong>Vectorized Aggregation</strong>. It scans the 500GB <strong>once</strong> and computes all 10,000 rules in a single mathematical sweep. It’s built-in, server-less, and provides a “Score.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M8WcoStOWtDqYM_1Zh6xpg.png" /><figcaption>Step 3 : Glue Data Quality System design(Image Credit : Author)</figcaption></figure><h4>Step 4: Incremental Data load and metadata file:</h4><p><strong>Question on Design?</strong> <strong>How do ensure that Pipeline get triggered when file all files are available?</strong></p><p><strong>The Scale Problem:</strong> What if Data Provide uploads 1000s of data files in S3, with every file complete pipeline is getting triggered? It would be waste of time/resousces.</p><p><strong>Solution:</strong> Data Provider first uploads all data/Metadata file in S3, once complete, it will add to entry in SQS, Crawler source is configured with <strong>“Crawl based on events: SQS ARN”. </strong>Now, <em>you don’t need Lambda</em> as pipeline is triggered after data file uploaded in source S3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OCRR9QDzLr-CAEZ4CxmHFA.png" /><figcaption>Step 4 : (Final Design)Incremental Data load and metadata file System design(Image Credit : Author)</figcaption></figure><h3>Low Level Design (LLD)</h3><p><strong>Final Design Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b8S-mhvii2VUGVp1DxK0ow.png" /></figure><h4>End-to-End Flow &amp; Special Logic</h4><p><strong>The “Vectorized” Logic</strong></p><p>To handle 1,000 columns, we don’t loop. We use <strong>Batching</strong> and <strong>Aggregation</strong>. In Glue Data Quality, this is handled by the engine, but if you were doing this in Spark, you’d use a “Single-Pass” aggregator.</p><p><strong>Sample DQDL (Data Quality Definition Language):</strong></p><pre>Rules = [<br>    # Schema checks<br>    ColumnCount = 1000,<br>    <br>    # Completeness checks<br>    IsComplete &quot;consumer_id&quot;,<br>    IsComplete &quot;address_line_1&quot;,<br>    <br>    # Value checks across 300M rows<br>    ColumnValues &quot;age&quot; between 18 and 120,<br>    <br>    # Custom SQL for complex logic<br>    CustomSql &quot;SELECT count(*) FROM primary WHERE email IS NULL&quot; &lt; 5000<br>]</pre><h4>AWS Glue Data Quality service limits</h4><ul><li><strong>You can have 2,000 rules in a ruleset.</strong> If your rulesets are larger, we recommend splitting into multiple rulesets.</li><li>The size of the ruleset is 65KB. If your rulesets are larger, we recommend splitting into multiple rulesets.</li><li>AWS Glue Data Quality collects statistics when you create a rule or analyzer. There is no cost associated with storing these statistics. However, there is a limit of 100,000 statistics per account, and these statistics will be retained for a maximum of two years.</li></ul><p><strong>Special Logic: Batching Shards</strong></p><p>When processing the final 300B records, we use <strong>Salting/Sharding</strong> to prevent “Hot Partitions” (where one Spark worker does all the work while others watch). We add a random “salt” column to distribute the 300M rows evenly across the cluster.</p><blockquote>Optimized data processing in spark will be covered in separate post.</blockquote><h3>Conclusion</h3><p>Validating 300 billion records isn’t about having the biggest computer; it’s about being the smartest about <em>when</em> you use it. By using <strong>Lambda</strong> as a bouncer, the <strong>Crawler</strong> as a librarian, and <strong>Glue Data Quality</strong> as the ultimate filter, we ensure marketing insights are always built on a foundation of gold, not garbage.</p><p>See you next time!</p><p><strong>You Know What To Do!</strong></p><ul><li><strong>Please share</strong> this with anyone that you think will be interested. It might help them, and it really helps me!</li><li>Please <strong>give me 50 claps</strong>! (Just hold down the clap button.)</li><li>Feel free to <strong>leave a comment</strong> 💬.</li><li>🙏 If you found this article helpful, <strong>subscribe and </strong>give it hit <a href="https://medium.com/@singh.sanjiv"><strong><em>Follow</em></strong></a><strong> </strong>— it helps more people discover it.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ec2018baecc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: Building a Scalable Surge Pricing Engine like Uber]]></title>
            <link>https://medium.com/@singh.sanjiv/system-design-building-a-scalable-surge-pricing-engine-like-uber-df05aef8f0e4?source=rss-30311cf4ee3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/df05aef8f0e4</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[uber]]></category>
            <dc:creator><![CDATA[Sanjiv Singh]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 16:00:14 GMT</pubDate>
            <atom:updated>2026-04-08T10:15:31.760Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered why your ride cost $15 at 4:00 PM but suddenly jumped to $45 at 5:00 PM when it started raining? That’s <strong>Surge Pricing</strong> in action. It’s not just a way to make more money; it’s a high-stakes balancing act of supply/demand and other factors.</p><p>Let’s dive into how we build a system that can calculate millions of prices per second without breaking a sweat.</p><blockquote><strong>Note:</strong> This design is based on my own understanding of systems design and professional experience. It is a conceptual architectural exercise and may or may not reflect the actual internal systems used by Uber.</blockquote><h4>The Core Problem</h4><p>Imagine a concert ends. 20,000 people open their apps simultaneously. There are only 200 drivers nearby. If the price stays at $15, everyone hits “Request,” and 19,800 people get a “No cars available” error.</p><p><strong>The core problem is this:</strong> How do we dynamically raise prices in real-time to encourage more drivers to head toward the “hot zone” while filtering out riders who aren’t in a hurry? We need to do this globally, accurately, and in under 100 milliseconds.</p><h4>Assumptions (What You Already Know)</h4><p>To keep this simple, I’m assuming you know the basics:</p><ol><li><strong>Microservices:</strong> The idea that different parts of an app (like “Payments” and “Surge”) talk to each other.</li><li><strong>Geospatial Data:</strong> Basically, Latitudes and Longitudes (GPS coordinates).</li><li><strong>Pub/Sub:</strong> A “Post Office” for data — one service sends a message (like Kafka), and others listen for it.</li></ol><h4>The Requirements</h4><p><strong>Functional</strong></p><ul><li><strong>Update Location:</strong> Drivers must send their GPS coordinates constantly.</li><li><strong>Get Estimate:</strong> Riders send their start/end points and get a price back immediately.</li></ul><p><strong>Non-Functional</strong></p><ul><li><strong>Low Latency:</strong> Calculating the surge “multiplier” (e.g., 1.5x) must take <strong>less than 100ms</strong>.</li><li><strong>Consistency:</strong> All riders in the same small neighborhood should see the same price.</li><li><strong>Availability:</strong> If the surge system fails, we default to “Normal Price” ($1.0x) rather than crashing.</li></ul><h4>Real Pain Point</h4><p>The hardest part is <strong>Spatial Smoothing</strong>. If you are on one side of a street, you shouldn’t pay $10 while someone 5 feet away pays $30 just because you’re in different “cells.”</p><h4>Scale:</h4><ul><li><strong>Users:</strong> 100 Million Monthly Active Users.</li><li><strong>Drivers:</strong> 5 Million Active Drivers.</li><li><strong>Write Pressure:</strong> 5M drivers sending a heartbeat every 10s = <strong>500,000 writes/sec.</strong></li><li><strong>Read Pressure:</strong> Peak times can hit <strong>100,000 ride requests/sec.</strong></li></ul><h4>Initial Design: The “Simple Database” Approach</h4><p>What if we just saved every driver’s location in a standard SQL database and counted them every time a rider asked for a price?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtWcPuxVe3Lc5kiV3kpXxg.png" /></figure><p><strong>Why this fails:</strong></p><ul><li><strong>Too Slow:</strong> SQL “Count” queries on millions of rows are slow. Doing this 100k times a second is impossible.</li><li><strong>Contention:</strong> With 500k writes/sec, the database would spend all its time locking rows and none of its time answering riders.</li></ul><h3>Step-by-Step Evolution</h3><h4>Step 1: Mapping the World (H3 vs. S2)</h4><p>We can’t treat the world as a flat map. We need to divide it into “Cells.”</p><ul><li><strong>Option X (S2 Squares):</strong> Google’s way. Great for math, but “diagonal” neighbors are further away than “side” neighbors.</li><li><strong>Option Y (H3 Hexagons):</strong> Uber’s choice. Every neighbor of a hexagon is the <strong>exact same distance away</strong>.</li><li><strong>Decision:</strong> <strong>Choose H3.</strong> It’s perfect for smooth geographic “rippling” effects.</li></ul><h4>Step 2: Handling the “Firehose” of Driver Updates</h4><p>Instead of a slow SQL DB, we use <strong>Redis</strong>.</p><ul><li><strong>Tool:</strong> Redis (In-memory store).</li><li><strong>Why?</strong> It can handle millions of operations per second.</li><li><strong>Data Structure:</strong> We store drivers in a <strong>Redis Sorted Set (ZSET)</strong> for each H3 cell. The “Score” is the timestamp. This lets us automatically ignore “zombie” drivers who haven’t sent a signal in 30 seconds.</li></ul><h4>Step 3: Calculating Surge (Offline vs. Online)</h4><p>Should we calculate the surge <em>the moment</em> a rider clicks the app? <strong>No.</strong> That’s too slow.</p><ul><li><strong>The Solution:</strong> We use an <strong>Aggregator Service</strong>.</li><li>It calculates a “Surge Map” — a simple list of Cell_ID: Multiplier—every few seconds and saves it in a <strong>Global Cache</strong>.</li></ul><h3>Low Level Design (LLD)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xWI913k1tik5B4uKPGPxjw.png" /></figure><h3>Users API Call: End-to-End Flows</h3><p><strong>Flow A: Driver Location Update (The Fan-In)</strong></p><p>To handle 500k writes/sec, we use a <strong>Lua Script</strong> in Redis. This makes the “check-in” atomic: it updates the driver’s location and their “last seen” timestamp in one go.</p><p><strong>Sample Lua Script (</strong><strong>update_driver.lua):</strong></p><pre>-- KEYS[1]: H3 Cell Key (e.g., drivers:cell_123)<br>-- ARGV[1]: Driver ID<br>-- ARGV[2]: Current Timestamp<br>-- ARGV[3]: Expiry limit (e.g., 30s)<br>-- Add driver to the current cell<br>redis.call(&#39;ZADD&#39;, KEYS[1], ARGV[2], ARGV[1])<br>-- Optional: Cleanup old drivers in this cell to keep memory low<br>local expired = ARGV[2] - ARGV[3]<br>redis.call(&#39;ZREMRANGEBYSCORE&#39;, KEYS[1], &#39;-inf&#39;, expired)</pre><p><strong>Flow B: Surge Aggregation</strong></p><p>Every 5 seconds, the <strong>Surge Aggregator(The Brain)</strong> “sweeps” Redis. It doesn’t just count one cell; it sums the center cell and its 6 neighbors to get a “smoothed” supply count.</p><p>Sample Aggregation Logic (Go):</p><pre>// 1. Get current cell ID from H3 library<br>neighbors := h3.KRing(currentCell, 1) // Center + 6 neighbors<br>totalAvailableDrivers := 0<br>for _, cell := range neighbors {<br>    // Get count of drivers who checked in within last 30s<br>    count := redis.ZCount(cell, now - 30, now)<br>    totalAvailableDrivers += count<br>}<br>// 2. Compare against Demand (from Kafka/Metrics)<br>multiplier := calculateMultiplier(totalAvailableDrivers, demandCount)<br>// 3. Update Global Surge Map<br>redis.Set(&quot;surge_map:&quot;+currentCell, multiplier)</pre><p>Above simple logic has considered only drivers available in current cell and neighbors cells.</p><h3>Advance topics:</h3><h3>1. In a real-world system like Uber’s, a driver 100 meters away (in the same cell) is much more valuable/cost efficient than a driver 2 kilometers away (in a neighbor cell) ?</h3><p><strong>Solution: Weighted H3 K-Rings</strong></p><p>We assign a <strong>Weight (W)</strong> to each “ring” of hexagons. The further the ring, the less those drivers “count” toward the local supply.</p><ul><li><strong>Ring 0 (Center Cell):</strong> Weight = <strong>1.0</strong> (100% value)</li><li><strong>Ring 1 (Immediate Neighbors):</strong> Weight = <strong>0.4</strong> (40% value)</li><li><strong>Ring 2 (Optional Extended Neighbors):</strong> Weight = <strong>0.1</strong> (10% value)</li></ul><h4>Aggregation Logic</h4><p>Instead of a simple ZCOUNT, the Aggregator performs a weighted sum. Here is how the logic evolves:</p><p><strong>Sample Logic:</strong></p><pre>func calculateWeightedSupply(targetCell H3Index) float64 {<br>    var weightedSupply float64 = 0.0<br>    // Ring 0: The Center (Weight 1.0)<br>    centerCount := redis.ZCount(targetCell, now - 30, now)<br>    weightedSupply += float64(centerCount) * 1.0<br>    // Ring 1: The 6 Neighbors (Weight 0.4 each)<br>    neighbors := h3.KRing(targetCell, 1) // Returns the 6 surrounding cells<br>    for _, cell := range neighbors {<br>        if cell == targetCell { continue } // Skip center<br>        <br>        neighborCount := redis.ZCount(cell, now - 30, now)<br>        weightedSupply += float64(neighborCount) * 0.4<br>    }<br>    return weightedSupply<br>}</pre><p>At 100k RPS, running this weighted math for every request is still heavy.</p><p>The <strong>Surge Aggregator</strong> runs this weighted math once every 5 seconds for every cell and stores the <em>Resulting Multiplier</em> in a <strong>Global Surge Map</strong>.</p><ul><li>The <strong>Ride Estimate Service</strong> doesn’t care about weights or neighbors.</li><li>It just asks: GET surge_multiplier:cell_123.</li><li>The complexity is hidden in the background “Pulse” of the aggregator.</li></ul><h3><strong>2. To handle a multi-factor surge (Weather, News, Time of Day, and Supply/Demand), we move away from simple math and into a Layered Multiplier Engine?</strong></h3><p>use <strong>Multiplicative Factors</strong> because they scale with the intensity of the situation.</p><p><strong>The Formula:</strong></p><blockquote>Final Surge = Base(Time) * Factor(Weather) * Factor(Event) * Factor(Supply/Demand)</blockquote><p><em>Example:</em></p><ul><li><strong>Base (5 PM Rush Hour):</strong> 1.2x</li><li><strong>Weather (Heavy Rain):</strong> 1.5x</li><li><strong>Supply/Demand (Low Drivers):</strong> 1.3x</li><li><strong>Total:</strong> 1.2 * 1.5 * 1.3 = 2.34x</li></ul><h4>Implementation:</h4><p><strong>Step A: The “Context” Store (Redis Hash)</strong></p><p>We maintain a “Context” for every H3 cell. This is updated by background workers.</p><ul><li><strong>Weather Worker:</strong> Every 5 minutes, it calls an API and updates Redis: HSET context:cell_123 weather_factor 1.5</li><li><strong>Event Worker:</strong> Scans a schedule. If a concert ends at 10 PM: HSET context:cell_123 event_factor 2.0</li></ul><p><strong>Step B: The Surge Aggregator</strong></p><p>The Aggregator runs every 5 seconds. It pulls the “Supply/Demand” from your Redis ZSETs and then “decorates” it with the context data.</p><p><strong>Sample Logic (Go):</strong></p><pre>func calculateFinalSurge(cellID string) float64 {<br>    // 1. Get Dynamic Supply/Demand Ratio<br>    sdMultiplier := calculateSDMultiplier(cellID) <br>    <br>    // 2. Fetch Environmental Context from Redis<br>    context := redis.HGetAll(&quot;context:&quot; + cellID)<br>    <br>    weather := parseFloat(context[&quot;weather_factor&quot;], 1.0)<br>    event := parseFloat(context[&quot;event_factor&quot;], 1.0)<br>    timeOfDay := getHistoricalBase(cellID, time.Now())<br>    // 3. Composite Calculation<br>    finalMultiplier := sdMultiplier * weather * event * timeOfDay<br>    <br>    // 4. Safety Caps (E6 Level Requirement)<br>    // Don&#39;t let the price go to 50x by accident!<br>    return math.Min(finalMultiplier, 5.0) <br>}</pre><h3>3. Handle “Price Elasticity” — i.e., lowering the surge if we notice riders are closing the app without booking?</h3><p>If you surge a neighborhood to<strong> 4x</strong>, but everyone immediately closes the app because it’s too expensive, you have <strong>0% conversion</strong>. The drivers are sitting idle, and the riders are walking.</p><p>To solve this, we introduce a <strong>Feedback Loop</strong> that monitors “Conversion Rate” in real-time and dampens the surge if the price is killing demand.</p><p><strong>1. The Metric: Conversion Rate (CVR)</strong></p><p>We track two events in <strong>Kafka</strong> to calculate the real-time health of a cell:</p><ol><li><strong>EstimateRequested</strong>: A rider opens the app and sees a price.</li><li><strong>RideBooked</strong>: That same rider clicks &quot;Request Ride.&quot;</li></ol><blockquote>CVR = Total Bookings/ Total Estimates</blockquote><p>If the historical CVR for a Monday at 10 AM is <strong>40%</strong>, but right now it has dropped to <strong>5%</strong>, your surge price is likely too high for that specific audience.</p><p><strong>2. The Logic: The “Dampening Factor”</strong></p><p>We introduce a new variable into our surge formula called the <strong>Elasticity Coefficient (</strong>A<strong>) </strong>.</p><p><strong>The New Formula:</strong></p><blockquote>Final Surge = (Supply/Demand * Weather * Event) * A</blockquote><blockquote>If CVR &gt;Threshold : A = 1.0 (No change).</blockquote><blockquote>If CVR &lt; Threshold: A slowly drops (e.g., 0.9, 0.8, 0.75) until bookings start happening again.</blockquote><p><strong>3. Implementation: The Stream Processor (Flink/RisingWave)</strong></p><p>At <strong>100k RPS</strong>, you cannot calculate CVR in a standard database. You need a <strong>Stream Processor</strong> to maintain a “Sliding Window” of conversion per H3 cell.</p><ol><li><strong>Ingestion:</strong> Kafka receives Estimate and Booking events.</li><li><strong>Aggregation:</strong> A Flink job groups these events by <strong>H3 Cell ID</strong> over a 60-second window.</li><li><strong>The Signal:</strong> If the “drop-off” rate (Estimates without Bookings) spikes, Flink writes an <strong>Elasticity Alert</strong> to a Redis Hash: HSET elasticity:cell_123 coefficient 0.8.</li></ol><p><strong>4. The Aggregator Logic</strong></p><p>The <strong>Surge Aggregator</strong> (the “Pulse” we discussed earlier) now pulls this coefficient before finalizing the price.</p><p><strong>Sample Logic (Go):</strong></p><pre>func getElasticityDampener(cellID string) float64 {<br>    // 1. Fetch the real-time elasticity from Redis<br>    // This is updated every 60s by our Stream Processor<br>    val, err := redis.Get(&quot;elasticity:&quot; + cellID).Float64()<br>    if err != nil {<br>        return 1.0 // Default: No dampening<br>    }<br>    <br>    // 2. Safety Check: Don&#39;t let elasticity drop the price BELOW $1.0x<br>    return math.Max(val, 1.0)<br>}<br>func calculateFinalPrice(cellID string) {<br>    rawSurge := calculateRawSurge(cellID) // Supply/Demand * Weather<br>    dampener := getElasticityDampener(cellID)<br>    <br>    finalSurge := rawSurge * dampener<br>    redis.Set(&quot;surge_map:&quot; + cellID, finalSurge)<br>}</pre><h3>Conclusion</h3><p>Designing Uber-style surge pricing is not just complex real-world problem — it’s about a <strong>smart pipeline</strong>. By using <strong>H3 Hexagons</strong> to map the world, <strong>Redis Lua scripts</strong> to handle the firehose of driver data, and an <strong>offline aggregator</strong> to pre-calculate prices, we ensure the system stays fast even during a New Year’s Eve storm.</p><p>See you next time!</p><p><strong>You Know What To Do!</strong></p><ul><li><strong>Please share</strong> this with anyone that you think will be interested. It might help them, and it really helps me!</li><li>Please <strong>give me 50 claps</strong>! (Just hold down the clap button.)</li><li>Feel free to <strong>leave a comment</strong> 💬.</li><li>🙏 If you found this article helpful, <strong>subscribe and </strong>give it hit <a href="https://medium.com/@singh.sanjiv"><strong><em>Follow</em></strong></a><strong> </strong>— it helps more people discover it.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df05aef8f0e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling to 100 Million: Designing a Real-Time Live User Counter for Global Streaming]]></title>
            <link>https://medium.com/@singh.sanjiv/scaling-to-100-million-designing-a-real-time-live-user-counter-for-global-streaming-aa19d0cbba5f?source=rss-30311cf4ee3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa19d0cbba5f</guid>
            <category><![CDATA[distributed-counter]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Sanjiv Singh]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 12:47:30 GMT</pubDate>
            <atom:updated>2026-03-25T16:34:13.787Z</atom:updated>
            <content:encoded><![CDATA[<p>Designing a live user counter for a global streaming platform (think World Cup Finals, Super Bowl, or a massive esports tournament) is a Engineer challenge. It looks simple — it’s just a counter, right? — but at a scale of <strong>100 Million concurrent users</strong>, traditional counting methods collapse.</p><p>Looking at this YouTube snapshot — how many concurrent users are currently watching this live stream?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0a5Vf3F3-I9sI-WdTSs7KA.png" /></figure><p>This post will walk you through the complete design journey, from a naive initial approach to a robust, eventually consistent, sharded architecture that delivers a smooth, 2-second refresh rate for distinct live viewers.</p><h3>1. Core Problem &amp; Constraints</h3><p>The primary challenge is <strong>High-Velocity write contention</strong> combined with <strong>Massive Read Fan-Out</strong>.</p><p>When 100 million users are watching a match, they are not a passive audience; their devices must constantly “check in” to prove they are still there. If these check-ins (heartbeats) funnel into a single database key, the system hits a “Hot Key” bottleneck, paralyzing the count. Simultaneously, all 100 million users expect to see that count update smoothly and accurately on their screens every few seconds.</p><h3>Assumptions (Reader Context)</h3><p>I assume the reader is familiar with basic system design concepts:</p><ul><li>Load Balancing (Layer 7)</li><li>Caching (Redis, Memcached)</li><li>Pub/Sub (Redis Pub/Sub, Kafka)</li><li>Persistent Connections (WebSockets, SSE)</li><li>The trade-offs of Eventual Consistency vs. Strong Consistency.</li></ul><h3>System Requirements</h3><p><strong>Functional Requirements</strong></p><ul><li>Display the <strong>Current Distinct Live Users</strong> count for a specific global match/stream.</li><li>The count must reflect <strong>Unique Viewers</strong> (not just total connection attempts).</li><li>The count displayed on the user’s screen must <strong>refresh every 2–3 seconds</strong>.</li></ul><h4>Non-Functional Requirements</h4><ul><li><strong>Scale:</strong> Support <strong>100 Million+ concurrent users</strong>.</li><li><strong>Availability:</strong> The counter must be 99.99% available; the stream failing is bad, but the counter failing during a peak moment erodes user trust.</li><li><strong>Latency:</strong> The aggregation and distribution of the count must happen within that 2-second window.</li><li><strong>Accuracy:</strong> Perfect precision is impossible and unnecessary at this scale. We aim for <strong>~99% accuracy</strong> (eventual consistency).</li></ul><h3>Key Scale Metrics</h3><ul><li><strong>Concurrency:</strong> 100M users.</li><li><strong>Heartbeat Interval:</strong> 30 seconds (User device checks in once per 30s).</li><li><strong>Write Ingestion Rate:</strong> 100M / 30s = <strong>~3.33 Million writes per second (WPS)</strong>.</li><li><strong>Read Broadcast Rate:</strong> 100M / 2s =(Conceptually) <strong>50M reads per second</strong>, but solved via Push/Broadcast.</li></ul><h3>Initial Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwwj-UId4a7kYgl9FCxGnQ.png" /><figcaption>Image Credit : Author</figcaption></figure><p>There are many issues in this design:</p><ul><li><strong>Hot Key Bottleneck:</strong> Redis is extremely fast, but it is single-threaded. It cannot process 3.33 million INCR operations per second on a single key. The CPU will hit 100% instantly, and the heartbeats will queue up, causing a massive outage.</li><li><strong>No Deduplication:</strong> INCR doesn&#39;t track identity. If a user refreshes their app or sends two heartbeats in a window, they are counted twice. This is not a &quot;Distinct Users&quot; count.</li></ul><h4>Concern 1: Solving the Hot Key with Sharding</h4><p>We cannot write to one key. We must write to many. We will divide the 100M users into <strong>1,000 shards</strong> based on their user_id.</p><p>shard_id = user_id % 1000</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zs9UwNVjshLlDAJCJ71xLg.png" /><figcaption>Image Credit : Author</figcaption></figure><h4>Concern 2<strong>: Solving Deduplication (Distinct Users)</strong></h4><p>We cannot just increment. We need a data structure that handles identity. A raw Bitmap (100M bits) is memory-intensive at ~12.5MB per time slot.</p><p><strong>HyperLogLog (HLL)</strong></p><ul><li>HLL is a probabilistic data structure that estimates cardinality (unique elements).</li><li>It uses a fixed, small amount of memory (<strong>12KB</strong> per HLL) to track millions of unique IDs with an error rate of &lt;1%.</li><li>Command: PFADD active_users:shard_14 user_uuid</li></ul><h4>Concern 3: Solving the 2-Second Refresh with a Sliding Window</h4><p>Our target refresh rate is 2 seconds, but our heartbeats only come every 30 seconds. To bridge this gap, we use a <strong>30-second Sliding Window</strong>, calculated every 2 seconds.</p><ol><li><strong>Temporal Granularity:</strong> We divide time into <strong>2-second slots</strong>.</li><li><strong>The Aggregator:</strong> Every 2 seconds, a background Go worker sums the HLL cardinality of the last 15 slots (15 * 2s = 30s).</li><li><strong>The Operation:</strong> It merges all 1,000 shards across all 15 slots.</li></ol><ul><li>Global_Temp = PFMERGE(node_0:slot_1...node_0:slot_15 ... node_49:slot_1...node_49:slot_15)</li><li>Live_Count = PFCOUNT(Global_Temp)</li></ul><h3>Low-Level Design &amp; Architecture Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BeOegrm_rj22YLA86kl1fg.png" /><figcaption>Image Credit : Author</figcaption></figure><h3>Path 1: Write Ingestion (The Fan-In)</h3><p>This path must handle the 3.33M WPS.</p><ol><li><strong>API :</strong> A large fleet of stateless ingestion servers receives the heartbeat.</li><li><strong>Hashing:</strong> The server calculates the shard_id and the current 2-second timestamp slot.</li><li><strong>Command:</strong> PFADD active_2s:shard_14 user_uuid</li></ol><ul><li><strong>(Sampling):</strong> To save infrastructure costs, you can <strong>sample 1% of heartbeats</strong> and multiply the final result by 100. This maintains adequate accuracy for a “Live Counter” while reducing Redis load by 99%</li></ul><h3>Path 2: Global Aggregation</h3><p>This path calculates the “Single Truth.”</p><ol><li><strong>Go Aggregator:</strong> A dedicated, single-instance background worker (with an active standby for failover) runs every 2 seconds.</li></ol><p><strong>2. Slide the Window:</strong> It identifies the <strong>15 most recent 2-second slots</strong>.</p><p><strong>3. Merge &amp; Count:</strong> It calls PFMERGE across all 1,000 shards for those 15 slots in the Redis Cluster. It then calls PFCOUNT on the temporary result. (This entire merge takes ~10–20ms on a high-spec Redis node).</p><p><strong>4. Pub/Sub Pulse:</strong> It publishes the resulting integer (e.g., 88,432,010) to a specialized <strong>Redis Pub/Sub</strong> channel: match_updates:123</p><p>To achieve a <strong>distinct live user count</strong> every 2 seconds with a 30-second heartbeat window, we need to perform a “Union” of multiple HyperLogLog (HLL) slots.</p><p>Doing this at the application level (fetching 15 slots * 1,000 shards) would create massive network overhead. Instead, we use <strong>Lua scripts</strong> to perform the heavy lifting inside Redis and a <strong>Go-style aggregator</strong> to pull the final results.</p><p>Below script runs on <strong>each individual Redis Shard</strong>. It takes the current timestamp and merges the last 15 “2-second slots” into one temporary HLL to get a distinct count for that shard.</p><p>Lua Script</p><pre>-- KEYS[1]: Base key name (e.g., &quot;active_users&quot;)<br>-- ARGV[1]: Current 2s-aligned timestamp (e.g., 1742640000)<br>-- ARGV[2]: Window size in seconds (e.g., 30)<br>-- ARGV[3]: Slot size in seconds (e.g., 2)<br>local base_key = KEYS[1]<br>local current_ts = tonumber(ARGV[1])<br>local window = tonumber(ARGV[2])<br>local step = tonumber(ARGV[3])<br>local slots_to_merge = {}<br>local temp_key = &quot;temp_union:&quot; .. current_ts<br>-- Identify the keys for the last 15 slots (30s / 2s = 15)<br>for i = 0, (window / step) - 1 do<br>    local ts = current_ts - (i * step)<br>    local slot_key = base_key .. &quot;:&quot; .. ts<br>    <br>    -- Only add to merge list if the slot actually exists<br>    if redis.call(&quot;EXISTS&quot;, slot_key) == 1 then<br>        table.insert(slots_to_merge, slot_key)<br>    end<br>end<br>if #slots_to_merge == 0 then<br>    return 0<br>end<br>-- Perform the union into a temporary HLL key<br>redis.call(&quot;PFMERGE&quot;, temp_key, unpack(slots_to_merge))<br>-- Get the distinct count<br>local count = redis.call(&quot;PFCOUNT&quot;, temp_key)<br>-- Cleanup: Set a short TTL on the temp key so it dies automatically<br>redis.call(&quot;EXPIRE&quot;, temp_key, 5)<br>return count</pre><p>Blow logic orchestrates the calls to all Redis nodes and publishes the final “Live Count.”</p><h4>The Steps:</h4><ol><li><strong>Calculate the Window:</strong> Every 2 seconds, determine the most recent 2-second aligned timestamp (e.g., time.Now().Unix() / 2 * 2).</li><li><strong>Parallel Execution:</strong> Use a WaitGroup or Worker Pool to execute the Lua script above on <strong>all Redis Shards</strong> simultaneously.</li><li><strong>Summation:</strong> Since the user IDs are partitioned by shard (user_id % 1000), the counts across shards are <strong>already distinct</strong>. You simply sum the integers returned by each shard.</li><li><strong>Publish:</strong> Send the final sum to the Pub/Sub channel.</li></ol><h4>Pseudo-Code (Go):</h4><pre>func startAggregator() {<br>    ticker := time.NewTicker(2 * time.Second)<br>    for range ticker.C {<br>        // 1. Current 2s slot<br>        currentTS := (time.Now().Unix() / 2) * 2<br>        <br>        var globalTotal int64<br>        var wg sync.WaitGroup<br>        var mu sync.Mutex<br>// 2. Query all Shards in Parallel<br>        for _, shard := range redisCluster.Shards() {<br>            wg.Add(1)<br>            go func(s RedisShard) {<br>                defer wg.Done()<br>                // Execute the Lua script on this specific shard<br>                count, _ := s.Eval(luaScript, []string{&quot;active_users&quot;}, currentTS, 30, 2).Int64()<br>                <br>                mu.Lock()<br>                globalTotal += count<br>                mu.Unlock()<br>            }(shard)<br>        }<br>        wg.Wait()<br>        // 3. Publish to Pub/Sub for the WebSocket Fleet<br>        redisMain.Publish(&quot;match_updates:123&quot;, globalTotal)<br>    }<br>}</pre><h3>Path 3: Read Broadcast (The Fan-Out)</h3><p>This path delivers the 2s refresh to the 100M users. We cannot let clients pull this data via HTTP; we must push it.</p><ol><li><strong>WebSocket Servers:</strong> A fleet of servers (e.g., 500 nodes, each holding 200k connections) holds the 100M connections open.</li><li><strong>Subscribe:</strong> Every node in the fleet subscribes <em>once</em> to the match_updates:123 Pub/Sub channel.</li><li><strong>The Broadcast:</strong> When the aggregator publishes the new “Tick,” every WebSocket node receives the number instantly and broadcasts it to all users connected to that specific server. The 2-second refresh is delivered with near-zero latency.</li></ol><p><em>We designed high-scalable and real-time Distinct user count on live-streaming platform.</em></p><p><em>Give a thumps up if you like the content and comment for suggestions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa19d0cbba5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Contest : System Design]]></title>
            <link>https://medium.com/@singh.sanjiv/leetcode-contest-system-design-5df2cd1c0277?source=rss-30311cf4ee3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5df2cd1c0277</guid>
            <category><![CDATA[leetcode-system-design]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Sanjiv Singh]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 04:02:42 GMT</pubDate>
            <atom:updated>2026-03-25T16:34:56.021Z</atom:updated>
            <content:encoded><![CDATA[<p>Designing a platform like LeetCode — supporting massive coding contests, untrusted code execution, and real-time leaderboards — is a system design challenge. It demands a sophisticated balancing act: extreme, bursty write concurrency; precise, low-latency execution; and a highly available, read-heavy state.</p><p>This post will take you through the complete journey, evolving from a simple functional architecture to a resilient, enterprise-grade system capable of handling 500,000 concurrent participants at scale.</p><blockquote><strong>Note:</strong> This design is based on my own understanding of systems design and professional experience. It is a conceptual architectural exercise and may or may not reflect the actual internal systems used by Leetcode.</blockquote><h3>Requirements and Scope</h3><h4>In-Scope (The Core Contest)</h4><ul><li><strong>Contest Lifecycle:</strong> Users can register for a scheduled contest, view locked problems at the exact start time, and participate in a <strong>90-minute</strong> event.</li><li><strong>Code Execution :</strong>A user submits code (supporting 15+ languages), which must run against a suite of hidden test cases.</li><li><strong>Synchronous Feedback:</strong> the user receives feedback: ACCEPTED, TLE (Time Limit Exceeded), WRONG_ANSWER, or RUNTIME_ERROR.</li><li><strong>Scoring &amp; Real-Time Leaderboard:</strong> Every accepted solution must atomically update the user’s score and dynamically recalculate their global rank among 500,000+ participants.</li></ul><h4>Out-of-Scope (Functional, but less critical)</h4><ul><li>Daily Problem exploration/discussion forums.</li><li>User profile management and premium plan billing.</li><li>Problem creation/curation interface for administrators.</li><li>Offline data analytics and historical contest archives.</li></ul><h3>The Scale</h3><ul><li><strong>Traffic:</strong> 10M DAU(Daily Active User) exploring problems.</li><li><strong>The Contest Spike:</strong> <strong>500,000+ users</strong> joining a single 90-minute contest simultaneously.</li><li><strong>Write Throughput:</strong> At peak, <strong>50,000+ code submissions per minute</strong>.</li><li><strong>Latency SLA:</strong> Sub-2 second feedback loop for code submissions.</li><li><strong>Data Volume:</strong> ~100 bytes per submission metadata. 50k subs/min * 100B = <strong>~5 MB/s ingestion rate</strong> (which is deceptively low; the issue is the processing cost per request, not the network bandwidth).</li></ul><h3>Initial Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*842j05Yv7YB_UnOo5Sjb_A.png" /><figcaption>Image Credit : Author</figcaption></figure><p><strong>Critical Flaws in this design:</strong></p><ol><li><strong>The Synchronous Bottleneck:</strong> The API Gateway is blocked, waiting up to 2 seconds for the worker to finish the execution (especially on TLE results). When 10k users submit in the same 5 seconds, your API Gateway will hit its connection limits and start dropping requests (<strong>503 Service Unavailable</strong>).</li><li><strong>The “Noisy Neighbor” Problem:</strong> A single greedy Docker container with while(true) can consume all CPU on the host, slowing down other users’ submissions and creating an unfair competitive environment.</li><li>PostgreSQL will perform well on standard counters, but 50,000+ concurrent updates to a single leaderboard table will lead to <strong>lock contention</strong> and transaction timeouts.</li></ol><h3>Resilience and Security</h3><p>We need to make two major changes: decouple the ingestion from the execution and solve the basic security isolation problem.</p><p><strong>Design Decisions (Evolve):</strong></p><ul><li><strong>Buffering Ingestion:</strong> We insert an asynchronous message queue (e.g., <strong>Kafka</strong> or SQS) between the API and the workers. The API durable-writes the submission metadata and immediately returns 202 Accepted.</li><li><strong>Basic Sandbox Security:</strong> Standard Docker containers share the host Linux kernel. This is a massive risk; a user could exploit a kernel 0-day to crash the entire EC2 node. We must introduce <strong>Namespaces</strong> and basic <strong>seccomp</strong> (secure computing) profiles to filter dangerous system calls.</li></ul><h3>Design Decisions</h3><h4>A. Code Execution options</h4><p>Lets look at Code Execution engine options</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-ecVK_OPjo2RwQcMjqTXg.png" /></figure><p><strong>Why Standard Containers are “too risky” </strong>For a platform like LeetCode, “Shared Kernel” isolation (Standard Docker) is a non-starter. We must prioritize security and native performance over startup time.</p><ul><li>We choose<strong> Firecracker MicroVMs.</strong> Developed by AWS, Firecracker uses KVM to spin up lightweight Virtual Machines in milliseconds. It provides true <strong>Hardware-Level Isolation</strong>. A user gets their own tiny, minimalist Linux kernel. Even with root access inside the VM, they are trapped. This offers the best balance of safety and native execution speed for competitive programming.</li></ul><h4>B. The “Noisy Neighbor” (CPU/RAM Capping):</h4><p>Competitive fairness demands deterministic resources.</p><ul><li>We leverage<strong> 1. cgroups (Control Groups) v2.</strong> This Linux kernel feature is used to enforce hard resource limits on each MicroVM/process. 2.<strong>Seccomp — </strong>Limits which system calls the Firecracker process can make to the host kernel</li><li><strong>Memory (</strong><strong>memory.max):</strong> A hard wall. If code tries to allocate 257MB on a 256MB limit, the process is killed instantly.</li><li><strong>CPU (</strong><strong>cpu.max):</strong> A governor. Even a recursive fork-bomb is throttled, preventing it from stealing cycles from other users’ submissions on the same host.</li></ul><h4>C.Server Leaderboard in realtime</h4><p>Rendering leaderboard directly from database is very bad idea.</p><p>We need quick <strong>in-memory</strong> and <strong><em>pre-calculated sorted</em></strong>(User Ranking) data that can be served fast.</p><p><strong>In-memory</strong> and <strong><em>pre-calculated sorted ?? </em></strong>You got it..right, we will leverage <strong>Redis Sorted Set (</strong>ZSET<strong>) </strong>to maintain contest leaderboard, with every user submission , will be add points in database and asynchronously update Leaderboard in Redis ZSET.</p><h4>D. Exactly-Once Scoring at Scale</h4><p>Redis ZSET is efficient data structure for ranking user score, but At 50,000 updates/minute, a single Redis ZSET (single-threaded) will become the global bottleneck. We need to think about sharding strategy</p><ul><li>User_id<strong>-based Sharding : </strong>if we bucket Redis ZSETs based on User_id, for user ranking and leaderboard creation, would need scan Score Buckets, which is costly and inefficient.</li><li>(We choose)<strong>Score-Based Sharding.</strong> We break the leaderboard into “Score Buckets” (e.g., 0–20 points, ….,161–180 points,181–200 points). Each bucket is managed by its own Redis Sorted Set.</li></ul><blockquote>let understand What happens when user submit code?</blockquote><ul><li><strong>The “Score Jump” Race Condition:</strong> When a user solves a problem, they “jump” from one bucket to another. For example current score in X and new earned points P, user will move from bucket X to X+P.</li><li>We must ensure they are <strong>not double-counted</strong> or <strong>lost</strong> during this transition.</li><li><strong>Atomic Operation (Lua):</strong> We use a <strong>Redis Lua Script</strong> to handle the “Remove from Old Bucket / Add to New Bucket / Update Total Counts” logic as a single, atomic operation on the Redis Primary. This guarantees consistency within the sharded leaderboard.</li></ul><blockquote>With bucketed approach How User Ranking is derived?</blockquote><ul><li>given user bucket , we will do sum of all members in buckets points &gt; user bucket point. and then iterate in user bucket how many users score &gt; user score.</li><li><strong>For Example: </strong>User A has score 170 and we have buckets for score range (0–20 points, ….,161–180 points,181–200 points)..user bucket in 161–180 and only 181–200 bucket &gt; user bucket range. so we count members in 181–200 buckets(we don’t need to iterate each member in bucket), than binary search how many are &gt; score in user bucket. bucket 0–20, 21–40 etc…will bot be scanned. Redis Lua Script for atomicity.</li></ul><blockquote>how Leaderboard (lets say top 100)will be derived?</blockquote><p>given, (0–20 points, ….,161–180 points,181–200 points) buckets, we will start from large range bucket to lower range bucket. In each bucket, we iterate through high to lower score members. As we reach 100, we terminate and return result. Redis Lua Script for atomicity.</p><h4>E. Prefer DynamoDB over RDBMS</h4><p>During a contest spike, we cannot afford the ‘Stop-the-World’ locking or connection limits of a traditional RDBMS. We need the <strong>predictable latency</strong> and <strong>sharding-by-design</strong> that DynamoDB provides to ensure every participant’s submission is recorded durably without lag</p><h4>F. Operational Resilience: Redis Failover and Recovery</h4><p>What if the Leaderboard Redis crashes?</p><ul><li><strong>The Strategy:</strong> Our “Source of Truth” is in <strong>DynamoDB</strong> (where we store submission metadata and ACCEPTED state). We rely on a <strong>DynamoDB Stream</strong> to trigger an idempotent consumer. If Redis fails and we promote a replica that is 2 seconds behind, the consumer will simply re-re-hydrate the last few seconds of traffic from the durable DynamoDB stream. This architecture guarantees that <strong>a zero-day Redis failure results in eventual consistency, not data loss.</strong></li></ul><h4>G. How to prevent user submission after 90-mins contest in over?</h4><p>We don’t want a “hard wall” only at the database level, as that would waste expensive compute resources on submissions that will eventually be rejected. We will the 90-minute rule at three specific points:</p><ul><li><strong>The Client Side :</strong> UI disables the “Submit” button and stops the timer at T+90.</li><li><strong>The API Gateway/Ingress : </strong>The API service maintains a cached ContestMetadata object (Load from database at boot, pub/sub to get ContestMetadatanew contest). When a submission arrives, the API checks: CurrentTime &lt;= ContestStartTime + 90 mins.</li><li><strong>The Consumer/Worker : </strong>use the <strong>Submission Timestamp</strong> (the time the API Gateway received and “stamped” the request), not the “Current Time” inside the Worker.</li></ul><h3>The Final Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qmizRi8rl673RhCM3JDug.png" /><figcaption>Image Credit : Author</figcaption></figure><h3>Schema Design</h3><p><strong>DynamoDB (Source of Truth)</strong></p><p><strong>Table: </strong><strong>UserContestState</strong> (Updated atomically only on ACCEPTED)</p><ul><li><strong>PK:</strong> CONTEST#&lt;contest_id&gt;</li><li><strong>SK:</strong> USER#&lt;user_id&gt;</li><li><strong>Attributes:</strong> total_score, problems_solved_map, finish_time, version (for Optimistic Locking).</li></ul><p><strong>Redis (Real-Time State — Low Latency/Ranking)</strong></p><p>Data Structure: ZSET (Sorted Set)</p><ul><li><strong>Key Name:</strong> leaderboard:contest_&lt;id&gt;:bucket_&lt;score_range&gt;</li><li><strong>Member:</strong> user_id</li><li><strong>Score:</strong> (TotalScore * 10^10) + (MaxTime - FinishTime) (Combining score and time handles tie-breaking automatically).</li></ul><p><em>We designed high-scalable, fast and resilient Coding contest platform.</em></p><p><em>Give a thumps up if you like the content and comment for suggestions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5df2cd1c0277" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design a Distributed Counter for Ads Ingestion]]></title>
            <link>https://medium.com/@singh.sanjiv/design-a-distributed-counter-for-ads-ingestion-734b98a9f10e?source=rss-30311cf4ee3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/734b98a9f10e</guid>
            <category><![CDATA[distributed-counter]]></category>
            <category><![CDATA[ads-click-aggregator]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Sanjiv Singh]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 12:03:16 GMT</pubDate>
            <atom:updated>2026-03-14T10:18:14.302Z</atom:updated>
            <content:encoded><![CDATA[<p>We will design a very simple system of Ads click Aggregation, where every time ads is shown on video is captured, billed to Ads owner. In this design, we will focus primarily on capturing all Ads Clicks and reporting to Advertiser. Areas like <em>Fraud or spam detection Demographic and geo profiling of users , Conversion tracking etc. are out-of scope.</em></p><blockquote>In the Ads world, <strong>every click is revenue</strong>. If you lose a Ads click, you lose money; if you double-count, you <em>commit billing fraud</em>.</blockquote><p>When 10M+ users are clicking simultaneously, a simple UPDATE counters SET count = count + 1 in a database is a recipe for system-wide failure.</p><h3>1. Requirements</h3><p>Lets define requirements.</p><h4>Functional</h4><ul><li><strong>Increment:</strong> Accurately increment the count for a specific ad_id.</li><li><strong>Query:</strong> Retrieve the aggregate count for an ad_id for real-time dashboards.</li><li><strong>Deduplication:</strong> Ensure a single click_id (idempotency key) is only counted once.</li></ul><h4>Non-Functional</h4><ul><li><strong>Scalability:</strong> Support <strong>10M+ RPS</strong> globally.</li><li><strong>Low Latency:</strong> Ingestion path must be <strong>sub-10ms</strong> to avoid user redirect lag.</li><li><strong>High Availability:</strong> The system must never “fail closed” (i.e., we should always accept the click).</li><li><strong>Accuracy:</strong> <strong>Exactly-once</strong> semantics for billing; eventual consistency (1–2s lag) for dashboards.</li></ul><h3>2. Back-of-the-Envelope Estimates</h3><ul><li><strong>Traffic:</strong> 10M clicks/sec.</li><li><strong>Payload:</strong> ~100 bytes per event (metadata: <strong>click_id</strong>, <strong>ad_id</strong>, <strong>user_id</strong>,<strong>video_id</strong>, timestamp, location, ads_position_in_video, time_spent_on_ad, is_skipped).</li><li><strong>Bandwidth:</strong> 10M times 100B = 1 GB/sec (Ingestion).</li><li><strong>Storage (Raw Logs):</strong> 1GB times 3600s = 3.6 TB/hour (for audit/cold storage).</li></ul><h3>3. API &amp; Schema Design</h3><h4>API</h4><ul><li>POST /v1/clicks: Receives the raw event.</li></ul><p>Returns 202 Accepted immediately after the event is persisted to the message bus.</p><ul><li>GET /v1/ads/{ad_id}/count:</li></ul><p>Returns the current aggregate.</p><h4>Database Schema (DynamoDB):</h4><p>We use two tables to separate “Hot Counts” from “Processing Metadata”:</p><ol><li><strong>AdCounters Table:</strong></li></ol><ul><li>PK: ad_id (String)</li><li>SK: shard_id (String) — <strong><em>Used for Hot Sharding</em></strong></li><li>count (Number)</li></ul><ol><li><strong>ConsumerMetadata Table:</strong></li></ol><ul><li>PK: partition_id (String) — <em>Kafka Partition ID</em></li><li>last_offset (Number) — <strong><em>To ensure Exactly-Once</em></strong></li></ul><h3>4. High-Level Design</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqZBW148h6ggsjTKjaAtGg.png" /><figcaption>Image Credit : Author</figcaption></figure><h3>5. Critical Design Decisions</h3><h4>A. Ingestion &amp; Buffering</h4><p>To hit 10M RPS, the Ingestion Service must be stateless. It performs two tasks:</p><ul><li><strong>Dedupe:</strong> Checks click_id in Redis (sharded by click_id + 1 Hour TTL). If it exists, it&#39;s a duplicate.</li><li><strong>Buffering:</strong> It doesn’t write to the DB. It pushes to <strong>Kafka</strong>, partitioned by ad_id. This ensures all clicks for the same ad go to the same worker for easy aggregation.</li></ul><h4>B. Solving the “Hot Shard” : The Celebrity Ad Problem</h4><p>If one viral ad (e.g., Super Bowl) gets 1M clicks/sec, a single row in DynamoDB will bottleneck.</p><ul><li><strong>Decision:</strong> Use <strong>Sub-Sharding</strong>. Instead of one row for Ad_123, we create 100 rows: Ad_123:S1 to Ad_123:S100.</li><li><strong>Writes:</strong> The worker randomly picks a shard to increment.</li><li><strong>Reads:</strong> The Read API performs a “Scatter-Gather,” summing all 100 shards.</li></ul><h4>C. Solving Exactly-Once (Kafka Offset in DB)</h4><p><em>What if the DynamoDB updates but the offset commit fails?</em></p><p>Standard Kafka offsets are stored in Kafka, leading to a race condition:</p><p><strong>Decision:</strong> Store the <strong>Kafka Offset</strong> inside the <strong>DynamoDB Transaction</strong>.</p><ul><li><strong>The Atomic Write:</strong></li></ul><pre>- Pseudo-logic inside a TransactWriteItems call<br>UPDATE AdCounters SET count = count + 500 WHERE ad_id = &#39;XYZ&#39;<br>UPDATE ConsumerMetadata SET last_offset = 5001<br>WHERE partition_id = &#39;P1&#39; AND last_offset &lt; 5001<br><br>-- If the worker crashes and restarts, it will re-read the batch. However, <br>-- the `ConditionExpression` (`last_offset &lt; 5001`) will fail, <br>-- preventing the duplicate increment.</pre><h4>D. Accuracy vs. Latency: The Redis Outage</h4><p>If the Redis dedupe layer goes down, we face a “CAP” trade-off.</p><ul><li><strong>Decision:</strong> <strong>Fail Open.</strong> In Ads, we prefer a tiny risk of double-counting over losing the revenue of the click entirely. We accept the click, log a “Dedupe Unavailable” flag, and perform a secondary batch-deduplication in our offline Data Lake (Hadoop/Snowflake) for final billing reconciliation.</li></ul><h3>6. Low-Level Worker Logic</h3><p>The “Worker” is where the heavy lifting happens. Instead of 1 -&gt; 1 updates, it uses <strong>Micro-Batching</strong>:</p><ul><li><strong>Poll</strong> 1000 messages from Kafka.</li><li><strong>Aggregate</strong> in-memory: {Ad_A: 400, Ad_B: 600}.</li><li><strong>Commit</strong> one transaction to DynamoDB containing the sums + the new high-watermark offset.</li></ul><p>Below is worker logic, how it atomically check last_offset and update counter and partition_wise kafka_offset.</p><pre>def process_kafka_batch(batch, partition_id):<br>    # 1. Aggregate counts in-memory<br>    aggregates = {}<br>    max_offset = -1<br>    <br>    for msg in batch:<br>        ad_id = msg.ad_id<br>        aggregates[ad_id] = aggregates.get(ad_id, 0) + 1<br>        max_offset = max(max_offset, msg.offset)<br><br>    # 2. Build the Atomic Transaction<br>    # We only update the counts IF the max_offset we just processed <br>    # is greater than what&#39;s already in the DB.<br>    <br>    transact_items = []<br>    <br>    # Add count updates for each Ad<br>    for ad_id, count in aggregates.items():<br>        transact_items.append({<br>            &#39;Update&#39;: {<br>                &#39;TableName&#39;: &#39;AdCounters&#39;,<br>                &#39;Key&#39;: {&#39;ad_id&#39;: {&#39;S&#39;: ad_id}},<br>                &#39;UpdateExpression&#39;: &#39;SET ad_count = ad_count + :inc&#39;,<br>                &#39;ExpressionAttributeValues&#39;: {&#39;:inc&#39;: {&#39;N&#39;: str(count)}}<br>            }<br>        })<br>    <br>    # Add the &quot;Check and Update&quot; for the Partition Offset<br>    transact_items.append({<br>        &#39;Update&#39;: {<br>            &#39;TableName&#39;: &#39;CounterMetadata&#39;,<br>            &#39;Key&#39;: {&#39;partition_id&#39;: {&#39;S&#39;: partition_id}},<br>            &#39;UpdateExpression&#39;: &#39;SET last_offset = :max_off&#39;,<br>            &#39;ConditionExpression&#39;: &#39;attribute_not_exists(last_offset) OR last_offset &lt; :max_off&#39;,<br>            &#39;ExpressionAttributeValues&#39;: {&#39;:max_off&#39;: {&#39;N&#39;: str(max_offset)}}<br>        }<br>    })<br><br>    # 3. Execute<br>    try:<br>        dynamodb.transact_write_items(TransactItems=transact_items)<br>    except ClientError as e:<br>        if e.response[&#39;Error&#39;][&#39;Code&#39;] == &#39;TransactionCanceledException&#39;:<br>            print(&quot;Duplicate batch detected via offset check. Skipping.&quot;)</pre><p><em>We designed a Distributed Counter for </em>Ad Click Aggregator<em> that is Scalable and accurate</em>.</p><p><em>Give a thumps up if you like the content and comment for suggestions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=734b98a9f10e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EventBrite : System Design at Global Scale]]></title>
            <link>https://medium.com/@singh.sanjiv/eventbrite-system-design-b4eaf1856d8b?source=rss-30311cf4ee3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4eaf1856d8b</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[eventbrite]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[ticketing-system]]></category>
            <dc:creator><![CDATA[Sanjiv Singh]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 10:29:32 GMT</pubDate>
            <atom:updated>2026-03-09T14:45:24.471Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post , we will cover EventBrite system design or other platform support organizing events and users make reservations. We will trace the path from a simple ticketing idea to a global marketplace handling millions of users and high-concurrency ticket drops that rival major music festivals.</p><p>This post covers the design constraints, the critical <strong>senior</strong> technical decisions, and the iterative steps that shaped our final architecture.</p><blockquote>Below design represents my own views, may not be same as EventBrite actual system architecture. if you find any gaps, lets me know in comments , I will incorporates.</blockquote><h3>Requirements and Scope</h3><p>At EventBrite, we operate at the intersection of a complex two-sided marketplace. We must balance the needs of <strong>organizers</strong> who create thousands of events and <strong>attendees</strong> who demand a flawless checkout experience, even during “hot” ticket drops.</p><h4>Functional Requirements (In-Scope)</h4><ul><li><strong>Event Management:</strong> Organizers can create pages, define multiple ticket tiers (VIP, Early Bird), and set precise inventory limits.</li><li><strong>Discovery:</strong> Attendees must be able to search globally based on keywords, categories, and <strong>geo-location</strong>.</li><li><strong>Booking and Payments:</strong> Facilitating a complete flow: selecting tickets, placing a time-limited <strong>reservation</strong>, and integrating with secure payment gateways like Stripe.</li><li><strong>Analytics:</strong> A real-time data layer to provide organizers with up-to-the-minute sales insights.</li></ul><h4>Non-Functional Requirements (The Constraints)</h4><ul><li><strong>Zero Overselling:</strong> If 10,000 tickets are available, we cannot allow 10,001 sales. This requires strict <strong>ACID transactions</strong>.</li><li><strong>Extreme Scalability:</strong> The system must handle spikes of <strong>100,000 requests per second (RPS)</strong> hitting a single event’s inventory.</li><li><strong>Global Low Latency:</strong> A user in Tokyo searching for London events needs a sub-100ms experience.</li><li><strong>Operational Freshness:</strong> Cancellations and inventory changes must reflect in search results within seconds.</li></ul><blockquote>Considering the scenario where millions of users are contending for a limited number of tickets for an event, consider the following design challenges:</blockquote><blockquote><strong>1. How do you protect the system from crashing when 10M users attempt to book tickets simultaneously?</strong></blockquote><blockquote><strong>2. Can your database survive 10M concurrent read/write requests? If relying on database locks, how will you mitigate resultant request timeouts?</strong></blockquote><blockquote><strong>3. How do you guarantee zero overselling or duplicate seat assignments without relying on refunds, as that results in a poor customer experience?</strong></blockquote><blockquote><strong>4. If a user fails to check out after adding tickets to their cart, how do you efficiently return that inventory to the available pool after a timeout?</strong></blockquote><h3><strong>Design Considerations</strong></h3><h4>1: Sharding Hot Inventories</h4><p>Our first major challenge was handling <strong>100k RPS</strong> in a relational database. A single UPDATE on one row causes lock contention that crashes connection pools.</p><p><strong>Decision:</strong> We implemented <strong>Dynamic Inventory Sharding</strong>.</p><ol><li><strong>Sharding Strategy:</strong> A 50k ticket limit is modeled as 500 rows (slots), each holding 100 tickets.</li><li><strong>Routing:</strong> Requests are routed to a specific slot based on user_id using consistent hashing.</li><li><strong>Result:</strong> This distributes the 100k RPS across 500 rows, reducing per-row contention to a manageable level for standard row-level locking.</li></ol><h4>2: “Double-Spend” Problem</h4><p>It allow a <strong>10-minute reservation</strong> for checkout. The challenge: ensuring the “Cleanup Worker” (releasing expired tickets) doesn’t collide with a late “Payment Worker” response.</p><p><strong>3-Step Distributed Handshake</strong>.</p><ol><li><strong>Soft Lock:</strong> Before calling the payment gateway, we update the status to payment_in_progress.</li><li><strong>Handshake:</strong> The Cleanup worker is programmed to <strong>ignore</strong> any ticket in payment_in_progress, even if the time has expired.</li><li><strong>Finalize:</strong> Only after the gateway confirms success is the ticket marked confirmed. If it fails, the ticket is returned to pending or expired.</li></ol><h4>3: Global Discovery at Scale</h4><p>With 5 million events, a single global search index is a bottleneck.</p><p><strong>Selective Replication and Cross-Cluster Search (CCS)</strong>.</p><ol><li><strong>Selective Replication:</strong> Local events (e.g., a yoga class) stay in regional clusters. Only “Global/High-Appeal” events are replicated via <strong>CCR</strong> to all regional clusters.</li><li><strong>CCS:</strong> If a user performs a global search, the local cluster fans out the query to remote regional clusters and aggregates the results.</li><li><strong>Result:</strong> This keeps regional shards lean and fast while providing global coverage without massive infrastructure overhead.</li></ol><h4>4: The High-Concurrency “Hot Path”</h4><p>The final evolution moved the “Hot Path” (inventory checks) completely out of the database and into an <strong>In-Memory layer</strong>.</p><ul><li><strong>Redis Lua Scripts:</strong> We use atomic Lua scripts to check and decrement inventory in Redis. This provides an immediate “Yes/No” to the user at microsecond speeds.</li><li><strong>Delayed Message Queues:</strong> Instead of heavy database CRON jobs, we use <strong>SQS/Kafka with delayed messages</strong>. When a reservation is made, a message &quot;wakes up&quot; 10 minutes later to check if the ticket needs to be re-released.</li></ul><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZigU2D1-YM4SATOKt03lw.png" /><figcaption>Image Credit : Author</figcaption></figure><h3>Flows</h3><h4>1. Create Event Flow (The Write Path)</h4><p>This flow ensures that when an organizer creates an event, the data is safely stored and then eventually indexed for global discovery.</p><ol><li><strong>Request Validation:</strong> The Event Creation Service receives a POST request, validating the organizer&#39;s credentials and event metadata (location, tiers, capacity).</li><li><strong>Transactional Outbox:</strong> To ensure consistency between the Database and Kafka, we use the <strong>Outbox Pattern</strong>. The service writes the event data to the Events table and a &quot;message&quot; to an Outbox table within the <strong>same ACID transaction</strong>.</li></ol><p>The database should be sharded by event_id to allow atomic transactions within a single shard.</p><pre>-- Inventory Table: Sharded by event_id<br>CREATE TABLE event_inventory (<br>    event_id INT NOT NULL,<br>    slot_id INT NOT NULL, -- Used for Row-Level Sharding<br>    available_count INT NOT NULL DEFAULT 0,<br>    version INT NOT NULL DEFAULT 0, -- Optimistic Locking<br>    PRIMARY KEY (event_id, slot_id)<br>);<br>-- Reservations Table<br>CREATE TABLE reservations (<br>    reservation_id UUID PRIMARY KEY,<br>    event_id INT NOT NULL,<br>    user_id INT NOT NULL,<br>    status ENUM(&#39;pending&#39;, &#39;payment_in_progress&#39;, &#39;confirmed&#39;, &#39;expired&#39;) DEFAULT &#39;pending&#39;,<br>    expires_at TIMESTAMP NOT NULL,<br>    version INT NOT NULL DEFAULT 0,<br>    INDEX (event_id, status),<br>    INDEX (expires_at)<br>);</pre><ol><li><strong>CDC Extraction:</strong> A <strong>Change Data Capture (CDC)</strong> worker (like Debezium) monitors the DB’s Write-Ahead Log (WAL), picking up the new entry and publishing it to the event_created Kafka topic.</li><li><strong>Search Indexing:</strong> An Index Worker consumes the message. If the event is flagged for &quot;Global Appeal,&quot; it is indexed into the <strong>Primary ES Cluster</strong> and replicated via <strong>CCR</strong> to regional clusters.</li></ol><h4>2. Search Event Flow (The Read Path)</h4><p>This flow prioritizes low latency by using regional shards and a two-stage retrieval process.</p><ol><li><strong>Geo-Filtering:</strong> The Search Service converts the user’s lat/long or city name into a <strong>Geohash</strong> or <strong>S2 Cell ID</strong>.</li><li><strong>Tier 1 Retrieval:</strong> The service first queries the <strong>Local Regional ES Cluster</strong>. It filters by geohash and performs a text match against the index.</li><li><strong>Tier 2 (Optional) Global Search:</strong> If the user’s intent is global (e.g., searching for a different city), the service initiates a <strong>Cross-Cluster Search (CCS)</strong> to fetch results from remote regional shards.</li><li><strong>Ranking &amp; Enrichment:</strong> The raw results from ES are sent to a <strong>Ranking Service</strong>. This service joins the event IDs with a <strong>Redis Cache</strong> to get real-time “Tickets Remaining” counts and re-orders the list based on user preferences.</li></ol><h4>3. Reservation Flow (The “Hot Path”)</h4><p>This is the most critical flow, designed to handle 100k RPS while guaranteeing zero overselling.</p><ol><li><strong>Waiting Room Check:</strong> The user hits the POST /reserve endpoint. If the system is under extreme load, the <strong>Virtual Waiting Room</strong> (Redis-based) issues a &quot;Position Token&quot; and makes the client wait.</li></ol><p><strong>Redis Lua Script : Atomic Reservation</strong></p><p>This script runs inside Redis to ensure the check-and-decrement operation is <strong>atomic</strong>, preventing overselling even with 100k+ concurrent requests.</p><pre>-- Keys: KEYS[1] = inventory_key, KEYS[2] = reservation_hash_key<br>-- Args: ARGV[1] = user_id, ARGV[2] = reservation_id, ARGV[3] = expires_at<br><br>local current_inventory = tonumber(redis.call(&#39;GET&#39;, KEYS[1]))<br><br>if current_inventory and current_inventory &gt; 0 then<br>    -- 1. Decrement inventory<br>    redis.call(&#39;DECR&#39;, KEYS[1])<br>    <br>    -- 2. Store reservation metadata for fast lookup<br>    redis.call(&#39;HSET&#39;, KEYS[2], ARGV[2], ARGV[1])<br>    <br>    -- 3. Set a TTL for the reservation ID to auto-expire in Redis<br>    -- (This triggers the cleanup worker if the user doesn&#39;t pay)<br>    redis.call(&#39;SETEX&#39;, &#39;lock:&#39; .. ARGV[2], 600, &#39;active&#39;)<br>    <br>    return 1 -- Success<br>else<br>    return 0 -- Sold out<br>end</pre><ol><li><strong>Atomic Lua Execution:</strong> Once it’s the user’s turn, the Reservation Service executes the <strong>Lua Script</strong> in Redis:</li></ol><ul><li>It checks if inventory_count &gt; 0.</li><li>If yes, it decrements the count and creates a <strong>short-lived lock</strong> in Redis.</li></ul><ol><li><strong>Asynchronous Persistence:</strong> The service returns a reservation_id to the user immediately. Simultaneously, it pushes a &quot;Reserved&quot; event to Kafka.</li><li><strong>Database Write &amp; Delay Trigger:</strong></li></ol><ul><li>A consumer picks up the Kafka message and inserts a row into the Reservations DB with a pending status.</li></ul><pre>-- Reservations Table<br>INSERT INTO reservations (<br>    reservation_id, <br>    event_id, <br>    user_id, <br>    status, <br>    expires_at, <br>    version<br>) VALUES (<br>    :reservation_id,  -- UUID generated by the Service<br>    :event_id, <br>    :user_id, <br>    &#39;pending&#39;,        -- Initial state<br>    NOW() + INTERVAL 10 MINUTE, <br>    0                 -- Start version<br>);</pre><ul><li>It also schedules a <strong>Delayed Message</strong> (10-minute timer) in SQS/Kafka to handle potential cleanup if the user never checks out.</li></ul><h4>4. Checkout &amp; Payment Flow</h4><p>This flow prevents the “Double-Spend” by using a specific state machine to protect tickets during active payment.</p><ol><li><strong>Initiate Checkout:</strong> The user submits payment details to the Checkout Service.</li><li><strong>State Transition (The Soft Lock):</strong> The service attempts to move the DB status from pending to payment_in_progress.</li></ol><pre>UPDATE reservations SET status = &#39;payment_in_progress&#39; <br>WHERE reservation_id = ? AND status = &#39;pending&#39; AND expires_at &gt; NOW();</pre><ul><li><strong>Logic:</strong> If rows_affected == 0, the reservation has already expired or is being handled elsewhere. The checkout is aborted.</li></ul><p><strong>3. External Payment:</strong> The service calls the <strong>Payment Gateway</strong> (Stripe/PayPal).</p><p><strong>4. Finalize (The Commit):</strong></p><ul><li><strong>Success:</strong> Update DB status to confirmed. This is a final state.</li><li><strong>Failure:</strong> Update DB status back to pending. This allows the user to try a different card before their 10 minutes are up.</li></ul><h4>5. Cleanup Worker Flow (The “Rollback to Inventory”)</h4><p>Instead of scanning the whole database, this worker is precision-targeted.</p><ol><li><strong>Delay Trigger:</strong> When the initial reservation was created, a <strong>Delayed Message</strong> was sent to <strong>SQS</strong> or a <strong>Kafka Delayed Topic</strong> with a 10-minute “invisible” timer.</li><li><strong>Expiration Check:</strong> After 10 minutes, the message becomes visible. The <strong>Cleanup Worker</strong> consumes it and checks the Database for that specific reservation_id.</li><li><strong>Status Validation:</strong></li></ol><ul><li>If status is confirmed or payment_in_progress: <strong>Do nothing</strong>. (If it&#39;s in progress, let the payment worker finish).</li><li>If status is pending and NOW() &gt; expires_at: <strong>Trigger Release</strong>.</li></ul><p><strong>The Release:</strong></p><ul><li>Update DB status to expired.</li><li>Increment the event_inventory count in the Database.</li><li><strong>Sync back to Redis:</strong> Increment the Redis inventory counter so the seat is immediately available for new searchers.</li></ul><p><em>We designed a system that is Scalable and efficient for organising Million of Events/Users at global scale.</em></p><blockquote><strong>Some task for you</strong>: Implement a <strong>proactive notification</strong> at the 9-minute mark. This not only improves the user’s chances of completing the purchase but also reduces the system load by increasing the conversion rate of “Pending” reservations, meaning the cleanup worker has fewer rollbacks to perform.</blockquote><p><em>Give a thumps up if you like the content and comment for suggestions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4eaf1856d8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>