<?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 Shiv Hari Baral on Medium]]></title>
        <description><![CDATA[Stories by Shiv Hari Baral on Medium]]></description>
        <link>https://medium.com/@shivharibaral?source=rss-be47f291f8d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*n2uBS1YuHsxKsAMq2POCCA.jpeg</url>
            <title>Stories by Shiv Hari Baral on Medium</title>
            <link>https://medium.com/@shivharibaral?source=rss-be47f291f8d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:30:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivharibaral/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[Building an AWS Lakehouse That Actually Works in Production]]></title>
            <link>https://shivharibaral.medium.com/building-an-aws-lakehouse-that-actually-works-in-production-b9d24a1ff656?source=rss-be47f291f8d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9d24a1ff656</guid>
            <dc:creator><![CDATA[Shiv Hari Baral]]></dc:creator>
            <pubDate>Tue, 19 Aug 2025 23:41:40 GMT</pubDate>
            <atom:updated>2025-08-19T23:41:40.589Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2RQSOjsH98IEtRJWjpjNA.png" /></figure><p>This guide shows a <strong>production-ready lakehouse</strong> on AWS — <strong>S3 + Apache Iceberg + Glue/Lake Formation + EMR/Glue + Athena/Redshift</strong> — with folder structures, code, and battle-tested tips for cost, performance, and governance.</p><h3>What is a “lakehouse” (in practice)?</h3><ul><li><strong>Data lake</strong> (cheap, durable storage): Amazon <strong>S3</strong></li><li><strong>Warehouse-like table semantics</strong> (schema, ACID, time travel): <strong>Apache Iceberg</strong> tables in S3</li><li><strong>Catalog &amp; permissions</strong>: <strong>AWS Glue Data Catalog</strong> + <strong>Lake Formation</strong></li><li><strong>Compute</strong>: <strong>EMR (or EMR Serverless)</strong> / <strong>AWS Glue</strong> (Spark) for batch &amp; streaming; <strong>Athena</strong> and/or <strong>Redshift</strong> to query</li><li><strong>Orchestration</strong>: <strong>MWAA (Airflow)</strong> or <strong>Step Functions</strong></li><li><strong>Governance &amp; security</strong>: <strong>Lake Formation</strong>, <strong>KMS</strong>, <strong>IAM</strong>, <strong>Macie</strong>, <strong>CloudTrail</strong></li></ul><p>Delta and Hudi are great alternatives; on AWS, <strong>Iceberg</strong> has first-class support across Athena, EMR, and Redshift.</p><h3>A real-world scenario</h3><p>You run an analytics platform for a multi-brand business. Sources include:</p><ul><li><strong>OLTP databases</strong> (orders, inventory) via <strong>DMS → S3</strong></li><li><strong>Clickstream</strong> &amp; app events via <strong>Kinesis/MSK → Firehose → S3</strong></li><li><strong>SaaS APIs</strong> (CRM, payments) via <strong>Airbyte/Fivetran/Lambda → S3</strong></li></ul><p>Teams need near-real-time KPIs, governed self-service BI, and ML-ready features. You’ll land raw data cheaply, transform it into trusted Iceberg tables, and expose it to <strong>Athena, Redshift, and SageMaker</strong>.</p><h3>S3 layout that scales</h3><p>Use <strong>zones</strong> and <strong>predictable keys</strong>:</p><pre>s3://company-lake/<br>  raw/                       # Immutable raw files (Bronze)<br>    source=crm/ingest_date=2025-08-19/part-000.snappy.parquet<br>    source=oltp/orders/ingest_date=2025-08-19/...<br>    source=events/app/partition_dt=2025-08-19/hour=15/...<br>  refined/                   # Cleaned, conformed (Silver) - Iceberg tables live here<br>    catalog=main/namespace=sales/table=orders/...<br>    catalog=main/namespace=crm/table=accounts/...<br>  curated/                   # Business-ready marts (Gold) - Iceberg<br>    catalog=main/namespace=bi/table=sales_daily/...<br>  checkpoints/               # Streaming checkpoints (Spark)<br>  tmp/                       # Scratch for CTAS/jobs; lifecycle to delete</pre><p><strong>Rules that help:</strong></p><ul><li><strong>Keep raw immutable.</strong> Fix issues downstream; never mutate raw.</li><li><strong>One Iceberg table per logical entity</strong> (refined/curated). Let <strong>Iceberg</strong> manage files and manifests.</li><li><strong>Lifecycle policies</strong>: raw older than <em>N</em> days → <strong>S3 Intelligent-Tiering</strong> or Glacier; tmp → auto-delete.</li></ul><h3>Table format &amp; partitioning (Iceberg)</h3><p>Iceberg gives you:</p><ul><li>Schema evolution (add, rename, reorder columns)</li><li><strong>MERGE/UPSERT</strong> with ACID guarantees</li><li>Time travel &amp; snapshots</li><li>Multi-engine reads (Athena, EMR, Redshift)</li></ul><p><strong>Partition spec tips</strong> (don’t over-partition):</p><ul><li>Use transforms (e.g., days(ts), months(ts), bucket( user_id, 32 ), truncate( campaign_id, 8 )).</li><li>Prefer <strong>a few dozen to a few hundred partitions per day</strong>, not tens of thousands.</li><li>Write <strong>128–512 MB</strong> files; compact small files periodically.</li></ul><h3>Security &amp; governance (default-on)</h3><ul><li><strong>SSE-KMS</strong> on all buckets; CMK with least-privilege key policy.</li><li><strong>Lake Formation</strong> for table/column/row-level access; use <strong>LF-Tags</strong> for PII.</li><li><strong>Private access</strong>: S3 Interface/ Gateway Endpoints; block public access.</li><li><strong>Macie</strong> to detect PII; <strong>CloudTrail</strong> for audit; <strong>Config</strong> for drift detection.</li></ul><h3>Catalogs &amp; sharing</h3><ul><li>Use <strong>Glue Data Catalog</strong> as the Iceberg catalog (catalog=main).</li><li>Cross-account sharing: <strong>Lake Formation resource links</strong> (no data copying).</li><li>Name namespaces sensibly: main.sales, main.crm, main.bi.</li></ul><h3>Batch processing with Spark (EMR/Glue)</h3><p><strong>Spark SQL: create an Iceberg table</strong></p><pre>-- On EMR/Glue Spark with Iceberg enabled<br>CREATE TABLE main.sales.orders<br>USING iceberg<br>PARTITIONED BY (days(order_ts))<br>TBLPROPERTIES (&#39;write.target-file-size-bytes&#39;=&#39;268435456&#39;) -- 256MB<br>AS<br>SELECT * FROM staging_orders; -- first load</pre><p><strong>Upserts / CDC merge</strong></p><pre>MERGE INTO main.sales.orders t<br>USING main.staging.orders_delta s<br>ON t.order_id = s.order_id<br>WHEN MATCHED AND s._op = &#39;D&#39; THEN DELETE<br>WHEN MATCHED AND s._op IN (&#39;U&#39;,&#39;I&#39;) THEN UPDATE SET *<br>WHEN NOT MATCHED AND s._op IN (&#39;I&#39;) THEN INSERT *;</pre><p><strong>Periodic compaction</strong></p><pre>CALL main.system.rewrite_data_files(<br>  table =&gt; &#39;sales.orders&#39;,<br>  options =&gt; map(&#39;min-input-files&#39;, &#39;50&#39;, &#39;target-file-size-bytes&#39;, &#39;268435456&#39;)<br>);</pre><h3>Streaming (near real-time)</h3><ul><li><strong>MSK/Kinesis</strong> → micro-batch with <strong>Spark Structured Streaming</strong> → <strong>Iceberg MERGE</strong>.</li><li>Use <strong>checkpointing</strong> (s3://.../checkpoints) + idempotent writes.</li><li><strong>Event schema</strong> in JSON/Avro with schema registry; evolve with discipline.</li></ul><p><strong>Streaming pseudocode (PySpark)</strong></p><pre>spark.conf.set(&quot;spark.sql.catalog.main&quot;, &quot;org.apache.iceberg.spark.SparkCatalog&quot;)<br>spark.conf.set(&quot;spark.sql.catalog.main.warehouse&quot;, &quot;s3://company-lake/refined&quot;)<br>spark.conf.set(&quot;spark.sql.catalog.main.catalog-impl&quot;,&quot;org.apache.iceberg.aws.glue.GlueCatalog&quot;)<br>spark.conf.set(&quot;spark.sql.extensions&quot;,&quot;org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions&quot;)</pre><pre>events = (spark.readStream<br>  .format(&quot;kafka&quot;)<br>  .option(&quot;kafka.bootstrap.servers&quot;, os.getenv(&quot;KAFKA_BROKERS&quot;))<br>  .option(&quot;subscribe&quot;, &quot;app.events&quot;)<br>  .load())</pre><pre>parsed = parse_and_validate(events)     # JSON → columns, apply contracts</pre><pre># Upsert into an Iceberg sink<br>(parsed.writeStream<br>  .format(&quot;iceberg&quot;)<br>  .option(&quot;checkpointLocation&quot;,&quot;s3://company-lake/checkpoints/app_events&quot;)<br>  .toTable(&quot;main.events.app&quot;))</pre><h3>Orchestration</h3><ul><li><strong>MWAA (Airflow)</strong> for dependency graphs, retries, SLAs, backfills.</li><li><strong>Step Functions</strong> for stateful batch workflows (e.g., DMS → validate → merge → compact).</li><li>Always add <strong>data quality checks</strong> before publishing to curated.</li></ul><p><strong>Airflow DAG sketch</strong></p><pre>with DAG(&quot;orders_daily&quot;, schedule=&quot;@hourly&quot;) as dag:<br>    dms_sync = AwsDmsTask(...)<br>    spark_refine = EmrServerlessStartJobRunOperator(...)<br>    dq_checks = GreatExpectationsOperator(...)<br>    publish_gold = EmrServerlessStartJobRunOperator(...)</pre><pre>    dms_sync &gt;&gt; spark_refine &gt;&gt; dq_checks &gt;&gt; publish_gold</pre><h3>Query &amp; serve</h3><ul><li><strong>Athena</strong> for ad-hoc SQL and light BI; point to <strong>Iceberg</strong> tables in Glue Catalog.</li><li><strong>Redshift Serverless</strong> can <strong>query Iceberg directly</strong> or <strong>COPY</strong> curated facts for heavy BI.</li><li><strong>QuickSight</strong> sits on Athena/Redshift.</li><li><strong>SageMaker</strong> or feature pipelines read curated Iceberg tables for ML.</li></ul><h3>Data quality &amp; contracts</h3><ul><li><strong>Contracts</strong>: define schemas, constraints, and SLAs with producers.</li><li><strong>Tests</strong>: Great Expectations/dbt tests (not_null, unique, relationships; plus custom).</li><li><strong>Monitors</strong>: freshness, volume, null rate, distribution drift; alert via CloudWatch + SNS.</li><li><strong>Quarantine</strong>: route bad records to s3://company-lake/quarantine/... with reason codes.</li></ul><h3>Cost &amp; performance checklist</h3><p><strong>Storage &amp; files</strong></p><ul><li>Parquet with <strong>Snappy</strong> (or <strong>ZSTD</strong> if your engines support it).</li><li>Target <strong>128–512 MB</strong> file sizes; compact small files on schedule.</li><li>Prune columns (projection) and partitions (predicate pushdown).</li></ul><p><strong>Compute</strong></p><ul><li><strong>EMR Serverless</strong> or managed scaling; spot where safe.</li><li>Cache dimension tables; broadcast small joins.</li><li>Keep shuffle under control (salt/skew hints, repartition by join keys).</li></ul><p><strong>Athena/Redshift</strong></p><ul><li>Athena: partition projection where helpful; prefer CTAS/INSERT OVERWRITE patterns for heavy reshapes.</li><li>Redshift: external Iceberg for lake queries; materialize hot marts inside Redshift for concurrency.</li></ul><p><strong>Ops</strong></p><ul><li>Lifecycle policies: raw → Intelligent-Tiering/Glacier; tmp → delete.</li><li>Budgets/alerts on S3, Athena, EMR; tag everything for showback.</li></ul><h3>DevOps &amp; environments</h3><ul><li><strong>Terraform</strong>: S3, KMS, Glue Catalog, Lake Formation grants, EMR/Glue, MSK, VPC endpoints.</li><li><strong>GitHub Actions</strong>: run tests, build Spark packages, register EMR jobs, publish Iceberg DDL.</li><li><strong>Config as code</strong>: table specs, partitioning, data contracts live in repo.</li></ul><p><strong>Terraform sketch (S3 bucket)</strong></p><pre>resource &quot;aws_s3_bucket&quot; &quot;lake&quot; {<br>  bucket = &quot;company-lake&quot;<br>  lifecycle_rule {<br>    id      = &quot;tmp-delete&quot;<br>    enabled = true<br>    prefix  = &quot;tmp/&quot;<br>    expiration { days = 7 }<br>  }<br>}<br>resource &quot;aws_s3_bucket_server_side_encryption_configuration&quot; &quot;sse&quot; {<br>  bucket = aws_s3_bucket.lake.id<br>  rule { apply_server_side_encryption_by_default { sse_algorithm = &quot;aws:kms&quot; } }<br>}</pre><h3>Common pitfalls (and fixes)</h3><ul><li><strong>Millions of tiny files</strong> → schedule <strong>Iceberg compaction</strong>; increase batch size.</li><li><strong>Over-partitioning</strong> → use Iceberg transforms (days(ts), bucket) instead of granular keys.</li><li><strong>Hot partitions</strong> → bucket on high-cardinality keys; balance write parallelism.</li><li><strong>Unbounded schema drift</strong> → enforce contracts; reject bad events; use schema registry.</li><li><strong>Cost spikes</strong> → right-size EMR; enable auto-suspend on Redshift; use Athena wisely (CTAS, projection).</li></ul><h3>Reference blueprint (services map)</h3><ul><li><strong>Storage</strong>: S3 (+ KMS, lifecycle)</li><li><strong>Table format</strong>: Apache Iceberg in S3</li><li><strong>Catalog &amp; ACLs</strong>: Glue Data Catalog + Lake Formation (LF-Tags, row/column policies)</li><li><strong>Ingest</strong>: DMS (CDC), MSK/Kinesis + Firehose/Lambda, Airbyte/Fivetran</li><li><strong>Transform</strong>: EMR / EMR Serverless / AWS Glue (Spark)</li><li><strong>Orchestrate</strong>: MWAA (Airflow) or Step Functions</li><li><strong>Query/Serve</strong>: Athena, Redshift (external Iceberg + internal marts), QuickSight</li><li><strong>ML</strong>: SageMaker or custom features from curated Iceberg tables</li><li><strong>Quality</strong>: Great Expectations / dbt tests + CloudWatch alerts</li><li><strong>Security</strong>: IAM, KMS, VPC endpoints, Macie, CloudTrail</li><li><strong>DevOps</strong>: Terraform, GitHub Actions, IaC modules</li></ul><h3>Final thoughts</h3><p>A lakehouse is less about logos and more about <strong>discipline</strong>: immutable raw data, governed Iceberg tables, reliable compaction, sane partitioning, and automated quality checks. Get those right and your teams can query with confidence, your ML pipelines stay reproducible, and your costs don’t creep.</p><p>#lakehouse # data-engineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9d24a1ff656" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[12 Surprisingly Practical Ideas for Building Agentic-AI Data Pipelines]]></title>
            <link>https://shivharibaral.medium.com/12-surprisingly-practical-ideas-for-building-agentic-ai-data-pipelines-babee8406ece?source=rss-be47f291f8d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/babee8406ece</guid>
            <dc:creator><![CDATA[Shiv Hari Baral]]></dc:creator>
            <pubDate>Fri, 15 Aug 2025 05:15:07 GMT</pubDate>
            <atom:updated>2025-08-15T05:15:07.826Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uOPUMn6V5WAM-8j4Yo42xQ.jpeg" /></figure><p>Agentic AI isn’t just “ask a model, get a string.” It’s a loop: <strong>observe → plan → act → learn</strong> — often across tools, data sources, users, and policies. That loop only works when your <strong>data pipeline</strong> is predictable, explainable, and cheap enough to run every minute of every day.</p><p>Below are twelve real-world ideas you can implement independently or as a playbook. Each idea explains <em>why it matters</em>, <em>how to build it</em>, and <em>pitfalls to avoid</em>. Keep your favorite stack; the patterns are stack-agnostic (Kafka/PubSub, dbt/Dagster/Airflow, Snowflake/BigQuery/Databricks, OpenSearch/pgvector/Pinecone, etc.).</p><h3>1) Treat “Context” as a First-Class Product (Not a Query)</h3><p><strong>Why:</strong> Agents succeed or fail on the <em>quality of the context</em> you hand them. A great LLM with noisy, stale, or mis-scoped context will hallucinate confidently.</p><p><strong>How:</strong> Build a “Context Builder” microservice. It pulls from multiple indices (keyword, vector, graph/features), respects a token/cost budget, dedupes by content hash, and returns a <strong>context pack</strong> artifact.</p><pre>{<br>  &quot;query&quot;: &quot;refund policy for EU customers&quot;,<br>  &quot;context_pack_id&quot;: &quot;ctx_9a…&quot;,<br>  &quot;budget_tokens&quot;: 2500,<br>  &quot;docs&quot;: [<br>    {&quot;id&quot;:&quot;doc_42&quot;,&quot;hash&quot;:&quot;sha256:…&quot;,&quot;title&quot;:&quot;EU Refund Policy v3&quot;,&quot;policy_tags&quot;:[&quot;GDPR&quot;,&quot;EU&quot;]},<br>    {&quot;id&quot;:&quot;faq_11&quot;,&quot;hash&quot;:&quot;sha256:…&quot;,&quot;title&quot;:&quot;Returns FAQ&quot;,&quot;policy_tags&quot;:[&quot;Public&quot;]}<br>  ],<br>  &quot;build_info&quot;:{&quot;time_ms&quot;:214,&quot;retrievers&quot;:[&quot;bm25&quot;,&quot;vector&quot;],&quot;model&quot;:&quot;e5-large-v2&quot;}<br>}</pre><p><strong>Pitfalls:</strong> Shoving everything into the prompt. If it doesn’t fit the budget, summarize or drop with clear rules. Always log context_pack_id for replay and audits.</p><h3>2) Contracts at the Edge: “Bad Data Sleeps Outside”</h3><p><strong>Why:</strong> Agents are fragile. A single malformed payload or silently changed upstream field can cascade into nonsense.</p><p><strong>How:</strong> Put <strong>JSON Schemas</strong> (or Avro/Protobuf) at the <em>ingress</em> of your pipeline (e.g., Kafka Connect, API Gateway). Validate, quarantine to a <strong>DLQ</strong>, and page on <em>schema drift</em> — not on broken dashboards two hours later.</p><p><strong>Pitfalls:</strong> “We’ll fix it downstream.” You won’t. You’ll normalize bugs into gold.</p><h3>3) Medallion Curation with Provenance</h3><p><strong>Why:</strong> You need raw truth for audits (Bronze), clean and deduped truth for joins (Silver), and job-ready truth for tasks/ML (Gold).</p><p><strong>How:</strong></p><ul><li><strong>Bronze:</strong> append-only, versioned Parquet/Delta; never mutate.</li><li><strong>Silver:</strong> types fixed, keys unified, late arrivals handled, <strong>SCD2</strong> where needed.</li><li><strong>Gold:</strong> task-specific marts/feature tables.</li></ul><p>Store <strong>provenance columns</strong> everywhere: source_system, content_hash, ingest_at, transform_version.</p><p><strong>Pitfalls:</strong> Over-denormalizing too early. Keep Silver tidy but flexible.</p><h3>4) Hybrid Retrieval: Vector and Keyword and Filters</h3><p><strong>Why:</strong> Vectors are great for semantics; keywords are great for exact terms and recency. You need both.</p><p><strong>How:</strong></p><ul><li>Vector index (pgvector/FAISS/Pinecone) + keyword index (Elasticsearch/OpenSearch/BM25).</li><li>Merge results with <strong>MMR</strong> (diversify) and apply <strong>policy filters</strong> (PII, jurisdiction, role).</li></ul><p><strong>Pitfalls:</strong> Single-index dogmatism. Hybrid wins in production.</p><h3>5) A Tool Ledger for Agents</h3><p><strong>Why:</strong> Agents call tools. Tools vary in quality, latency, and cost. Track them like you track credit scores.</p><p><strong>How:</strong> Log every tool call with latency_ms, success, retries, cost_usd, and <strong>reward</strong> (did it help?). Rank tools by scenario. Penalize frequent failures via routing.</p><p><strong>Pitfalls:</strong> Treating all tools as equal. They’re not.</p><h3>6) Golden Tasks + Replay Harness</h3><p><strong>Why:</strong> You need a stable yardstick to know if changes help or hurt (embeddings, chunking, prompts, models).</p><p><strong>How:</strong> Create a small, audited set of <strong>golden tasks</strong> (inputs + expected outcomes + required citations). Every change triggers a <strong>replay</strong> against them with diff reports (pass/fail, latency, cost).</p><p><strong>Pitfalls:</strong> Evaluating purely by “it feels smarter.” Feelings drift; golden tasks don’t.</p><h3>7) Budgeting: Tokens, Latency, and Dollars</h3><p><strong>Why:</strong> Costs creep. Latency creeps. Then your CFO creeps into your standup.</p><p><strong>How:</strong> Give every request a <strong>budget</strong> (tokens, milliseconds, dollars). Context builder trims or summarizes to fit; routing chooses model tier (cheap vs. best). Persist <em>actuals</em> for showback.</p><p><strong>Pitfalls:</strong> Global caps with no per-tenant throttle. One noisy neighbor takes everyone down.</p><h3>8) Tenancy and Residency: Security by Architecture</h3><p><strong>Why:</strong> Multi-tenant + sensitive data = accidental leakage risk.</p><p><strong>How:</strong></p><ul><li>Tenant-scoped buckets and indices.</li><li>RBAC/ABAC at both data and retrieval layers.</li><li>Per-region storage if residency applies.</li><li><strong>Row/column masking</strong> for PII; encrypt secrets in KMS/Key Vault.</li></ul><p><strong>Pitfalls:</strong> Relying on app logic alone for isolation.</p><h3>9) Content Hashing Everywhere</h3><p><strong>Why:</strong> You’ll embed, chunk, and fetch the same content repeatedly.</p><p><strong>How:</strong> Derive a <strong>content hash</strong> (sha256) for each blob <em>before</em> embedding or chunking. Cache embeddings by hash; cache LLM responses by (hash, instruction). Use hash to dedupe retrieval results.</p><p><strong>Pitfalls:</strong> Recomputing embeddings on identical content. Money bonfire.</p><h3>10) Drift Radar for Retrieval (Not Just Models)</h3><p><strong>Why:</strong> Pipelines decay even when models don’t: content ages, chunk sizes change, vendors tweak APIs.</p><p><strong>How:</strong> Track distributions: embedding norms, top-K overlap vs. last week, retrieval hit rate, context length, and doc staleness. Alert on drift beyond thresholds.</p><p><strong>Pitfalls:</strong> Only monitoring model accuracy. Retrieval drift silently wrecks answers.</p><h3>11) Observability Like You Mean It</h3><p><strong>Why:</strong> If you can’t see it, you can’t fix it at 2 a.m.</p><p><strong>How:</strong></p><ul><li><strong>Traces:</strong> OpenTelemetry-style spans for agent steps; trace_id end-to-end.</li><li><strong>SLIs/SLOs:</strong> freshness, p95 latency, error rate, token cost, success/goal completion.</li><li><strong>Runbooks:</strong> DLQs, backfills, hotfix prompts, rollbacks.</li></ul><p><strong>Pitfalls:</strong> Logging prompts without masking. Redact or tokenize PII immediately.</p><h3>12) “State-Aware” CI for Data Changes</h3><p><strong>Why:</strong> Rebuilding the world on every PR is slow and expensive.</p><p><strong>How:</strong> Use <strong>state awareness</strong> (e.g., dbt’s state:modified+) to run tests/builds only for impacted models. Lint contracts, validate sources, and generate docs as part of CI. Block merges without updated contracts.</p><p><strong>Pitfalls:</strong> Treating data like app code but skipping tests. It’s worse than no tests.</p><h3>Putting It Together (A Minimal Reference Flow)</h3><pre>[Producers/Agents/Tools] <br>     │ (validated JSON Schemas)<br>     ▼<br>[Kafka/Kinesis]──►[Bronze: S3/ADLS/GCS (Parquet/Delta, append-only)]<br>     │<br>     ├─(dbt/Spark)►[Silver: clean, deduped, SCD2, provenance]<br>     │<br>     ├─(Enrich)►[Embeddings, NER, Safety Tags]<br>     │<br>     ├─►[Hybrid Index: Vector + Keyword + Filters]<br>     │<br>     └─►[Gold: task marts, features, pre-aggregations]<br> <br>[Context Builder API] → retrieve + diversify + budget + policy → **context_pack**<br>[Agent Runtime] → tools with guardrails → telemetry → back to Kafka</pre><pre>Observability: OpenTelemetry, Prometheus/Datadog, SLO dashboards<br>Governance: RBAC/ABAC, masking, KMS, audit trails<br>CI/CD: contracts + state-aware builds, docs/lineage, runbooks</pre><h3>Starter Kit</h3><ul><li><strong>Pick 10 golden tasks</strong> and stand up a <strong>replay harness</strong>.</li><li>Add <strong>JSON Schema</strong> at ingest with a DLQ; turn on alerts for drift.</li><li>Implement a <strong>Context Builder</strong> that returns a <strong>context pack</strong> artifact.</li><li>Enable <strong>content hashing</strong> and caching for embeddings.</li><li>Add <strong>one SLO dashboard</strong>: freshness, latency p95, token cost, and retrieval hit-rate.</li></ul><p>Ship that first. You’ll immediately improve reliability, lower costs, and make every future model upgrade safer.</p><h3>Final Take</h3><p>Agentic AI isn’t magic; it’s <strong>data discipline with feedback loops</strong>. If you standardize context, enforce contracts, log provenance, evaluate with replays, and budget for latency/cost, your agents will be <em>useful, steerable, and trustworthy</em> — not just impressive demos.</p><p>Build the foundation; your agents (and users) will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=babee8406ece" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Real-World Data Pipeline for Agentic AI?]]></title>
            <link>https://shivharibaral.medium.com/how-to-build-a-real-world-data-pipeline-for-agentic-ai-71c8fd46aadd?source=rss-be47f291f8d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/71c8fd46aadd</guid>
            <dc:creator><![CDATA[Shiv Hari Baral]]></dc:creator>
            <pubDate>Fri, 15 Aug 2025 04:58:57 GMT</pubDate>
            <atom:updated>2025-08-15T05:00:25.987Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*MbF4bWKSFlPsL4VPVsTzyw.jpeg" /></figure><p><em>From raw signals to reliable, low-latency context for tools-using LLM agents</em></p><p>Agentic AI systems don’t just answer questions — they <strong>plan, decide, and take actions</strong> using tools (APIs, databases, search) in multi-step loops. That power only works when your <strong>data pipeline</strong> is rock-solid: fresh, trustworthy, observable, and cheap enough to run at scale.</p><p>Below is a pragmatic, end-to-end blueprint you can ship in production. It’s tool-agnostic (swap in the stack you prefer) and packed with patterns used in the wild.</p><h3>0) Start with the product, not the stack</h3><p><strong>Define outcomes first.</strong><br> What must the agent do? Examples: answer policy questions with citations; triage tickets; reconcile SKUs; generate call summaries; fill forms. For each:</p><ul><li><strong>Latency budget:</strong> interactive (&lt;1–2s), near-real-time (&lt;15s), batch.</li><li><strong>Freshness:</strong> how fresh must the data be (seconds/minutes/hours)?</li><li><strong>Cost ceiling:</strong> $/request, $/tenant/day.</li><li><strong>Auditability:</strong> what must you retain (prompts, docs, decisions)?</li></ul><p>Write these as <strong>SLOs</strong>; your pipeline will exist to meet them.</p><h3>1) Model your agent data (schemas &amp; contracts)</h3><p>Agent loops emit rich telemetry. Standardize it.</p><p><strong>Core entities</strong></p><ul><li>session, agent_state, message, tool_call, observation, context_pack, memory_write, reward/eval.</li></ul><p><strong>Required fields</strong><br> trace_id, tenant_id, user_id, timestamp, model_version, policy_flags, latency_ms, cost_usd, pii_masked:boolean.</p><p><strong>Contract everything.</strong> Use JSON Schema (or Protobuf/Avro). Reject or quarantine non-conforming events at ingress.</p><pre>// tool_call event (simplified)<br>{<br>  &quot;trace_id&quot;: &quot;uuid&quot;,<br>  &quot;ts&quot;: &quot;2025-08-14T18:03:22Z&quot;,<br>  &quot;agent_id&quot;: &quot;claims-bot&quot;,<br>  &quot;tool&quot;: &quot;claims.search&quot;,<br>  &quot;input&quot;: {&quot;query&quot;:&quot;denials in TX last 30d&quot;},<br>  &quot;output&quot;: {&quot;count&quot;: 238, &quot;ids&quot;:[...]},<br>  &quot;status&quot;: &quot;ok&quot;,<br>  &quot;latency_ms&quot;: 134,<br>  &quot;cost_usd&quot;: 0.0012<br>}</pre><h3>2) Ingest: real-time + batch, with guardrails</h3><ul><li><strong>Streaming:</strong> Agent traces, tool I/O, clicks, and feedback → <strong>Kafka/Kinesis/PubSub</strong> → land raw to <strong>object storage</strong> (S3/ADLS/GCS) as <strong>Parquet/Delta</strong>.</li><li><strong>Batch:</strong> Schedulers (<strong>Airflow/Dagster</strong>) pull SaaS, CRM/ERP, web, and policy sources on SLAs.</li><li><strong>Edge validation:</strong> JSON Schema + <strong>Great Expectations</strong>/<strong>dbt tests</strong>. Bad data → <strong>DLQ</strong>; do not silently fix in place.</li></ul><p><strong>Best practice:</strong> <strong>Idempotent</strong> producers with <strong>content hashes</strong>; include <strong>source pointers</strong> (URL, file key, API cursor) for replay.</p><h3>3) Normalize &amp; curate (Bronze → Silver → Gold)</h3><p>Adopt the <strong>medallion</strong> pattern:</p><ul><li><strong>Bronze:</strong> raw, append-only, versioned.</li><li><strong>Silver:</strong> clean types, dedupe, handle late arrivals, unify keys, <strong>SCD2</strong> where needed.</li><li><strong>Gold:</strong> task-oriented marts (e.g., “answerable_docs”, “eligible_invoices”), features, and pre-aggregations.</li></ul><p>Use <strong>dbt</strong> for modular SQL semantics; for heavy lifting or joins across large tables, use <strong>Spark/Databricks/Flink</strong>. Keep <strong>late-arriving</strong> and <strong>duplication rules</strong> explicit.</p><h3>4) Enrich for agents (embeddings, NER, safety)</h3><p>Agentic systems need <strong>semantic signals</strong> in addition to relational data.</p><ul><li><strong>Chunk &amp; embed</strong> unstructured content (policies, manuals, tickets).</li><li>Add <strong>NER/entity resolution</strong> (customer ↔ account; drug ↔ NDC; product ↔ SKU).</li><li>Compute <strong>safety/PII labels</strong> (policy tags) for filtering and redaction.</li><li><strong>Version everything</strong>: embedding model, chunker settings, normalization rules.</li></ul><p><strong>Tip:</strong> Store doc_id, content_hash, embed_model_version, chunk_idx, policy_tags[] on each chunk.</p><h3>5) Indexing &amp; memory</h3><ul><li><strong>Hybrid search is non-negotiable.</strong> Combine <strong>vector</strong> (FAISS/pgvector/Pinecone) + <strong>keyword</strong> (OpenSearch/Elasticsearch/BM25) + <strong>filters</strong>.</li><li>Keep <strong>tenant-scoped</strong> indexes; enforce RBAC/ABAC in the retrieval layer.</li><li>Maintain <strong>feature/memory stores</strong>:</li><li><strong>Semantic memory:</strong> embeddings with time/recency boosts.</li><li><strong>Facts/preferences:</strong> relational store or feature store (Feast/Snowflake).</li><li><strong>Short-term state:</strong> Redis with TTL.</li></ul><h3>6) Context assembly (RAG/MCP layer)</h3><p>Your <strong>context builder</strong> is the heart of agent reliability.</p><ul><li>Retrieve candidates across sources; <strong>diversify</strong> (MMR), <strong>dedupe</strong> by content_hash.</li><li>Apply <strong>policy overlays</strong> (privacy, tenure, geography).</li><li><strong>Budgeting:</strong> stay within token/cost budget (summarize, drop low-gain chunks).</li><li>Emit a <strong>context_pack</strong> artifact: doc ids, hashes, versions. This fuels audit and evals.</li></ul><pre>def build_context(query, budget_tokens):<br>    hits = hybrid_search(query, k=40)<br>    hits = diversify(hits)<br>    hits = filter_by_policy(hits, user_ctx)<br>    chunks = summarize_to_budget(hits, budget_tokens)<br>    log_context_pack(chunks)   # ids, hashes, versions<br>    return chunks</pre><h3>7) Orchestration &amp; serving</h3><ul><li><strong>Batch orchestration:</strong> Airflow/Dagster with <strong>state-aware</strong> runs (run only impacted models).</li><li><strong>Streaming compute:</strong> Spark Structured Streaming/Flink for joins, compaction, and enrichment.</li><li><strong>Services:</strong> build retrieval + context APIs (FastAPI/gRPC).</li><li><strong>Agent runtime guardrails:</strong> <strong>timeouts, retries, circuit breakers, rate limits</strong>, plus <strong>tool fallbacks</strong> and <strong>caching</strong> by content hash.</li></ul><h3>8) Observability &amp; evaluation (don’t skip this)</h3><ul><li><strong>Tracing:</strong> OpenTelemetry-style spans for agent steps; trace_id everywhere.</li><li><strong>SLIs/SLOs:</strong> freshness, retrieval hit-rate, token cost, latency p95, error rate, success/goal completion.</li><li><strong>Quality:</strong></li><li><strong>Offline</strong>: golden tasks, replay harness, diff on context packs.</li><li><strong>Online</strong>: answer usefulness, citation coverage, tool-failure rate, refusal/safety metrics.</li><li><strong>Drift:</strong> watch embedding distributions, prompt length, cache hit rate, doc staleness.</li></ul><pre># dbt example: freshness + custom tests<br>sources:<br>  - name: crm<br>    tables:<br>      - name: tickets<br>        freshness: {warn_after: {count: 2, period: hour}}<br>tests:<br>  - name: ticket_semantic_validity<br>    config: {severity: warn}</pre><h3>9) Governance, safety, and privacy</h3><ul><li><strong>PII/PHI:</strong> detect &amp; mask at ingest; tokenize or redact in logs; store secrets in <strong>KMS/Key Vault</strong>; private networking.</li><li><strong>Access:</strong> RBAC/ABAC on datasets and indices; <strong>data contracts</strong> with upstreams.</li><li><strong>Audit:</strong> immutable logs of <strong>prompts</strong>, <strong>context packs</strong>, <strong>model versions</strong>, <strong>decisions</strong>.</li><li><strong>Residency:</strong> per-tenant buckets and indices if needed.</li></ul><p><strong>Rule of thumb:</strong> you should be able to answer “<em>Why did the agent make this decision?</em>” with a reproducible trace.</p><h3>10) Performance &amp; cost controls</h3><ul><li><strong>File layout:</strong> compact small files; <strong>OPTIMIZE + Z-ORDER</strong> (Delta) or clustering/partitioning (Snowflake/BigQuery).</li><li><strong>Incremental everything:</strong> dbt incremental <strong>MERGE</strong>; materialized views; pre-aggregations for hot paths.</li><li><strong>Cache:</strong> embeddings &amp; retrieval results by content_hash; LLM response cache with TTL and feature flags.</li><li><strong>Model tiering:</strong> route to fast/cheap vs. accurate/expensive models by task and budget.</li><li><strong>Right-size compute:</strong> auto-suspend warehouses; autoscaling; spot pools where safe.</li></ul><h3>11) Developer experience (DX) &amp; change safety</h3><ul><li><strong>Monorepo</strong> (infra + code + dbt) with <strong>Terraform</strong>; <strong>CI/CD</strong> that runs only impacted models (state:modified+).</li><li><strong>Contracts → tests → reviews.</strong> No contract, no merge.</li><li><strong>Data catalogs &amp; docs</strong>: auto-publish dbt docs/lineage; tag datasets with owner, SLA, sensitivity.</li><li><strong>Runbooks:</strong> incident playbooks, rollback steps, backfill procedures.</li></ul><h3>12) Rollout plan (a practical 30–60–90)</h3><p><strong>First 30 days</strong></p><ul><li>Define SLOs &amp; schemas; stand up streaming ingest + Bronze; add minimal dbt project; wire basic monitoring.</li></ul><p><strong>Days 31–60</strong></p><ul><li>Build Silver (dedupe, SCD2); ship first <strong>context builder</strong>; add embeddings &amp; hybrid search; launch golden-task evals.</li></ul><p><strong>Days 61–90</strong></p><ul><li>Gold marts + feature store; harden observability (SLO dashboards, alerts); optimize cost (compaction, caching, tiering); document v1 runbooks.</li></ul><h3>Reference architecture (textual)</h3><pre>[Producers] -&gt; [Kafka] -&gt; [Landing (S3/ADLS/GCS: Bronze)]<br>                 |--&gt; Validations (JSON Schema/GE)<br>[Batch SaaS/API/SFTP] --(Airflow/Dagster)--&gt; Bronze</pre><pre>Bronze --(Spark/dbt)--&gt; Silver (cleaned, deduped, SCD2)<br>Silver --(Enrich)--&gt; Embeddings/NER/Safety Tags<br>Silver+Embeddings --&gt; [Hybrid Index: Vector + Keyword]</pre><pre>[Context Builder API] -&gt; fetch + diversify + budget + policy -&gt; Context Pack<br>[Agent Runtime] -&gt; LLM/Tools with guardrails -&gt; Telemetry (Kafka)</pre><pre>Silver/Gold/Features -&gt; Warehouse (Snowflake/BigQuery/Databricks SQL)<br>Observability -&gt; Prometheus/Datadog + OpenTelemetry + SLO dashboards<br>Governance -&gt; RBAC/ABAC, KMS, Audit, Catalog</pre><h3>Common failure modes (and fixes)</h3><ul><li><strong>Hallucinated citations:</strong> log <strong>context packs</strong> and require doc ids/hashes; eval for citation coverage.</li><li><strong>Stale answers:</strong> freshness SLOs + staleness filters; automated backfills; doc TTL in retrieval.</li><li><strong>Cost blow-ups:</strong> token/latency budgets; summarization gates; model tiering; cache by hash.</li><li><strong>Schema drift outages:</strong> upstream <strong>contracts</strong> + DLQs; late-arrival handling; contract-aware tests in CI.</li><li><strong>Tenant leakage:</strong> enforce tenancy at <strong>index &amp; query layers</strong>; add data residency checks to the context builder.</li></ul><h3>Best-practice checklist</h3><ul><li>Product SLOs: freshness, latency, cost, auditability</li><li>JSON Schema / contracts at ingest; DLQ path</li><li>Medallion curation with dbt (+ incremental)</li><li>Embedding/version strategy; content hashing</li><li>Hybrid search (vector + keyword) with policy filters</li><li>Context builder with budgets + context pack logs</li><li>Guardrails: timeouts, retries, circuit breakers, rate limits</li><li>Observability: traces, SLO dashboards, drift monitors</li><li>Governance: RBAC/ABAC, masking, KMS, audit trails</li><li>Cost levers: compaction, Z-ORDER/partitioning, caching, model tiering</li><li>CI/CD + IaC; state-aware tests; catalogs/docs</li><li>Runbooks for incidents, backfills, rollbacks</li></ul><h3>Final thought</h3><p>Agentic AI succeeds or fails on <strong>data reliability</strong>. Flashy prompts help, but <strong>clean contracts, curated corpora, reproducible context, and ruthless observability</strong> are what make agents safe, fast, and useful at scale. Build the foundation first — then your agents can confidently take action.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71c8fd46aadd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is an Intelligent Agent in AI? And How Do They Work?]]></title>
            <link>https://shivharibaral.medium.com/what-is-an-intelligent-agent-in-ai-and-how-do-they-work-6428724c8034?source=rss-be47f291f8d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6428724c8034</guid>
            <dc:creator><![CDATA[Shiv Hari Baral]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 04:17:46 GMT</pubDate>
            <atom:updated>2025-08-13T04:17:46.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q1C85aaeQhJpai6aqP5u9A.png" /></figure><p>If you’ve ever watched a robot vacuum find its way around a chair, asked a chatbot to draft an email, or seen traffic lights adapt to rush hour — you’ve met an <strong>intelligent agent</strong>. It’s not sci-fi; it’s a practical idea that powers a lot of modern AI.</p><p>This article breaks down what an intelligent agent is, how it thinks, and how you can reason about (or even design) one yourself — without drowning in math.</p><h3>The one-sentence definition</h3><p>An <strong>intelligent agent</strong> is a system that <strong>perceives</strong> its environment through sensors, <strong>decides</strong> what to do using some policy or reasoning, and <strong>acts</strong> through effectors to <strong>maximize a performance measure</strong> over time.</p><p>Think of it as a loop:</p><blockquote><strong><em>Sense → Think → Act → (Learn) → Repeat</em></strong></blockquote><h3>The anatomy of an agent</h3><ul><li><strong>Environment</strong>: The world the agent lives in (a web page, a factory floor, a game, your living room).</li><li><strong>Sensors</strong>: How it perceives (camera, microphone, API responses, user input).</li><li><strong>Actuators/Effectors</strong>: How it takes actions (motors, keystrokes, API calls, database writes).</li><li><strong>Policy / Agent Function</strong>: The mapping from perceptions to actions (could be rules, a search/planning algorithm, or a neural network).</li><li><strong>Performance Measure</strong>: What “good” looks like (cleaned area per minute, user satisfaction, revenue, reward).</li></ul><p>As an agent gains <strong>autonomy</strong>, it relies less on hardcoded rules and more on learning from experience.</p><h3>Environments vary (and shape the design)</h3><p>When you design or analyze an agent, first classify the environment:</p><ul><li><strong>Observable vs. partially observable</strong>: Does the agent see everything? (Chess is observable; the real world isn’t.)</li><li><strong>Deterministic vs. stochastic</strong>: Is the next state predictable? (Assembly line vs. traffic.)</li><li><strong>Episodic vs. sequential</strong>: Are decisions isolated or long-term? (Spam filter vs. stock trading.)</li><li><strong>Static vs. dynamic</strong>: Does the world change while you think? (Web pages vs. moving pedestrians.)</li><li><strong>Discrete vs. continuous</strong>: Are actions/states countable? (Board moves vs. steering angles.)</li><li><strong>Single vs. multi-agent</strong>: Are there other agents with their own goals? (Poker, markets, multi-robot teams.)</li></ul><p>These choices determine whether you need planning, probabilistic reasoning, fast reflexes, or deep learning.</p><h3>The main species of agents (from simple to savvy)</h3><ol><li><strong>Simple reflex agents</strong></li></ol><ul><li>“If condition, then action.”</li><li>Example: Thermostat — if temperature &lt; 21°C, turn heat on.</li></ul><ol><li><strong>Model-based reflex agents</strong></li></ol><ul><li>Maintain a <strong>state</strong> (“model”) of the world to handle partial observability.</li><li>Example: Robot vacuum remembers where it has been to avoid re-cleaning.</li></ul><ol><li><strong>Goal-based agents</strong></li></ol><ul><li>Use search/planning to achieve goals.</li><li>Example: Route planner finds a path with constraints (no tolls, fastest route).</li></ul><ol><li><strong>Utility-based agents</strong></li></ol><ul><li>Optimize a <strong>utility function</strong> that trades off multiple objectives (speed, safety, comfort, cost).</li><li>Example: Self-driving car balancing ETA with risk and passenger comfort.</li></ul><ol><li><strong>Learning agents</strong></li></ol><ul><li>Improve performance via data and experience.</li><li>Example: Recommendation system that adapts to user clicks.</li></ul><blockquote><em>Many real systems blend these: model-based + goals + utility + learning.</em></blockquote><h3>How agents “think” (four common brains)</h3><ol><li><strong>Rules / Expert Systems</strong></li></ol><ul><li>Easy to explain, fast for narrow domains.</li><li>Weak at handling uncertainty or complexity spikes.</li></ul><p><strong>2. Search &amp; Planning</strong></p><ul><li>Build a future: simulate states, pick a plan (BFS/DFS, A*, heuristic search, STRIPS-like planners).</li><li>Great when you have a good model and clear goals.</li></ul><p><strong>3. Probabilistic reasoning</strong></p><ul><li>Reason under uncertainty (Bayes nets, HMMs, particle filters).</li><li>Useful for tracking, diagnosis, and noisy sensors.</li></ul><p><strong>4. Learning (ML &amp; RL)</strong></p><ul><li><strong>Supervised/unsupervised</strong>: map inputs to outputs; discover structure.</li><li><strong>Reinforcement Learning (RL)</strong>: learn a policy π(a|s) to <strong>maximize cumulative reward</strong>.</li><li><strong>Model-free</strong> (Q-learning, policy gradients): learn from trial and error.</li><li><strong>Model-based</strong>: learn or leverage a world model to plan ahead.</li><li>Core dilemmas: <strong>exploration vs. exploitation</strong>, delayed rewards, non-stationary environments.</li></ul><h3>A minimal mental model (PEAS)</h3><p>Before you build or evaluate an agent, write a <strong>PEAS</strong> spec:</p><ul><li><strong>P</strong>erformance: What are you optimizing? (e.g., delivery time, safety incidents, cost)</li><li><strong>E</strong>nvironment: Where does it operate? (e.g., city map with traffic, API rate limits)</li><li><strong>A</strong>ctuators: What can it do? (e.g., send requests, move, buy/sell)</li><li><strong>S</strong>ensors: What can it observe? (e.g., GPS, camera, logs, user prompts, API responses)</li></ul><p><strong>Example (robot vacuum):</strong><br> Performance: area cleaned/hour, battery life, collisions minimized<br> Environment: apartment with furniture and pets (dynamic, partially observable)<br> Actuators: wheels, suction power modes<br> Sensors: bumpers, lidar/camera, battery level</p><h3>Pseudocode: the sense–think–act loop</h3><pre>state ← initial_state()<br>policy ← initialize_policy()         # rules, planner, or learned model<br>while running:<br>    perception ← sense()<br>    state ← update_state(state, perception)    # model-based update<br>    action ← policy(state)                     # choose using rules/plans/ML<br>    act(action)<br>    policy ← learn(state, action, reward?)     # optional learning step</pre><p>This skeleton covers everything from a CLI bot that calls APIs, to a warehouse robot, to an LLM-powered assistant.</p><h3>Where you already see agents</h3><ul><li><strong>Robot vacuums &amp; drones</strong>: SLAM for mapping; obstacle avoidance; coverage planning.</li><li><strong>Recommender systems</strong>: “Act” by ranking content; “sense” via clicks and dwell time.</li><li><strong>Trading bots</strong>: Perceive market ticks; act with orders; learn a strategy under constraints.</li><li><strong>Autonomous cars</strong>: Perception (vision/lidar) → prediction → planning → control.</li><li><strong>LLM agents</strong>: Use language models as the “brain” to plan, call tools (search, code, databases), remember context, and execute multi-step tasks.</li></ul><h3>Common pitfalls (and how to avoid them)</h3><ul><li><strong>Reward hacking</strong>: The agent finds a loophole in your metric.</li><li><em>Fix:</em> add constraints, penalize side effects, use human feedback.</li><li><strong>Distribution shift</strong>: The world changes; performance degrades.</li><li><em>Fix:</em> monitoring, continual learning, simulators, guardrails.</li><li><strong>Partial observability</strong>: Acting on incomplete info causes mistakes.</li><li><em>Fix:</em> maintain a belief/state, fuse sensors, reason probabilistically.</li><li><strong>Latency vs. optimality</strong>: Perfect planning is too slow.</li><li><em>Fix:</em> receding-horizon control, fast heuristics, learned policies.</li></ul><h3>Want to build one? A simple path</h3><ol><li><strong>Define PEAS.</strong> Write the objective and constraints clearly.</li><li><strong>Start simple.</strong> Implement a rule-based baseline; measure it.</li><li><strong>Add a model or planner</strong> if you need foresight or constraints.</li><li><strong>Introduce learning</strong> where rules break (ranking, perception, control).</li><li><strong>Instrument everything.</strong> Log decisions, rewards, failures; create dashboards.</li><li><strong>Iterate.</strong> Tighten the loop between performance metrics and design.</li></ol><h3>Conclusion</h3><p>An intelligent agent is any system that <strong>senses</strong>, <strong>decides</strong>, and <strong>acts</strong> to optimize a goal. The right design depends on the <strong>environment</strong> and <strong>objective</strong>. In practice, powerful agents blend <strong>models</strong>, <strong>goals</strong>, and <strong>learning</strong> — plus great engineering around monitoring, safety, and iteration. If you think in terms of <strong>PEAS</strong> and the <strong>sense–think–act</strong> loop, you’ll have a practical compass for understanding (and building) agents — from robot vacuums to LLM tool-using assistants.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6428724c8034" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Apache Kafka: Intuitive Explanation and Hands-On Tutorial]]></title>
            <link>https://shivharibaral.medium.com/getting-started-with-apache-kafka-intuitive-explanation-and-hands-on-tutorial-f38cfe297a56?source=rss-be47f291f8d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f38cfe297a56</guid>
            <dc:creator><![CDATA[Shiv Hari Baral]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 21:41:38 GMT</pubDate>
            <atom:updated>2025-06-16T21:41:38.420Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*OzsTGjbLtSV-qyb13pcE2g.png" /></figure><p>Apache Kafka is a distributed streaming platform that lets you publish, subscribe to, store, and process records in real time. At its core, Kafka is a fault-tolerant, high-throughput, low-latency system for handling continuous data streams — think of it as a highly scalable, distributed “message bus” or “commit log” that powers everything from activity tracking to real-time analytics and microservice communication.</p><h3>1. Kafka’s Building Blocks</h3><h3>1.1 Brokers</h3><p>A <strong>broker</strong> is a single Kafka server. In production you’ll have a cluster of brokers for redundancy and scaling. Each broker is responsible for storing and serving data for the partitions it “owns.”</p><h3>1.2 Topics &amp; Partitions</h3><ul><li><strong>Topic</strong>: a category or feed name (e.g. user-signups) to which messages are published.</li><li><strong>Partition</strong>: an ordered, append-only sequence of messages within a topic. Partitions let Kafka distribute load across brokers and maintain order per partition.</li></ul><blockquote><strong><em>Analogy:</em></strong><em> Think of a topic as a book, and partitions as chapters. Multiple readers (consumers) can read from different chapters (partitions) in parallel, but within each chapter the pages (messages) are in strict order.</em></blockquote><h3>1.3 Producers &amp; Consumers</h3><ul><li><strong>Producer</strong>: an application that writes (publishes) messages to a topic.</li><li><strong>Consumer</strong>: an application that reads (subscribes to) messages from one or more topics.</li></ul><p>Producers push data into Kafka; consumers pull data out.</p><h3>2. How Data Flows Through Kafka</h3><ol><li><strong>Producer Sends Message</strong></li></ol><ul><li>Configure a producer with the broker addresses.</li><li>Call produce(topic, key, value) to append a record to the end of a partition’s log.</li></ul><p><strong>2. Broker Appends to Log</strong></p><ul><li>The broker writes the record to disk in a segment file under its log.dirs.</li><li>Acks from the broker can be tuned (e.g., wait for leader only, or all in-sync replicas) to balance durability vs latency.</li></ul><ol><li><strong>Consumer Polls for Data</strong></li></ol><ul><li>Consumers belong to a <strong>consumer group</strong>. Within a group, partitions are automatically assigned so each message is delivered to only one consumer.</li><li>Call poll() (or an async to-thread wrapper) to fetch new records.</li></ul><ol><li><strong>Offset Management</strong></li></ol><ul><li>Kafka tracks each consumer’s “offset” (position) in each partition.</li><li>By committing offsets (automatically or manually), the consumer can restart without reprocessing old messages.</li></ul><h3>3. Installation &amp; Getting Started</h3><h3>3.1 Running with Docker</h3><p>A minimal docker-compose.yml:</p><pre>version: &#39;3.8&#39;<br>services:<br>  kafka:<br>    image: bitnami/kafka:latest<br>    environment:<br>      - KAFKA_ENABLE_KRAFT=yes<br>      - KAFKA_CFG_PROCESS_ROLES=broker,controller<br>      - KAFKA_CFG_NODE_ID=1<br>      - KAFKA_CFG_CONTROLLER_QUORUM_VOTERS=1@kafka:9093<br>      - KAFKA_CFG_LISTENERS=PLAINTEXT://0.0.0.0:9092,CONTROLLER://0.0.0.0:9093<br>      - KAFKA_CFG_ADVERTISED_LISTENERS=PLAINTEXT://localhost:9092<br>      - KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP=PLAINTEXT:PLAINTEXT,CONTROLLER:PLAINTEXT<br>      - KAFKA_CFG_CONTROLLER_LISTENER_NAMES=CONTROLLER<br>      - ALLOW_PLAINTEXT_LISTENER=yes<br>    ports:<br>      - &quot;9092:9092&quot;<br>      - &quot;9093:9093&quot;</pre><pre>docker-compose up -d</pre><h3>3.2 Creating a Topic</h3><p>Via the CLI:</p><pre>kafka-topics \<br>  --bootstrap-server localhost:9092 \<br>  --create \<br>  --topic my-topic \<br>  --partitions 3 \<br>  --replication-factor 1</pre><p>Or programmatically with the AdminClient in Python.</p><h3>4. Writing Your First Producer &amp; Consumer</h3><h3>4.1 Producer (Python example)</h3><pre>from confluent_kafka import Producer<br>producer = Producer({&#39;bootstrap.servers&#39;: &#39;localhost:9092&#39;})<br>producer.produce(&#39;my-topic&#39;, key=&#39;user1&#39;, value=&#39;hello, Kafka!&#39;)<br>producer.flush()</pre><h3>4.2 Consumer (Python example)</h3><pre>from confluent_kafka import Consumer<br>c = Consumer({<br>    &#39;bootstrap.servers&#39;: &#39;localhost:9092&#39;,<br>    &#39;group.id&#39;: &#39;my-group&#39;,<br>    &#39;auto.offset.reset&#39;: &#39;earliest&#39;<br>})<br>c.subscribe([&#39;my-topic&#39;])<br>while True:<br>    msg = c.poll(1.0)<br>    if msg and not msg.error():<br>        print(f&quot;{msg.key().decode()}: {msg.value().decode()}&quot;)<br>c.close()</pre><h3>5. Core Concepts Explained</h3><h3>5.1 Durability &amp; Replication</h3><ul><li><strong>Replication factor</strong> determines how many brokers hold copies of each partition.</li><li>If one broker fails, a replica can be promoted to leader to ensure no data loss.</li></ul><h3>5.2 Ordering Guarantees</h3><ul><li>Within a partition, message order is guaranteed.</li><li>Across partitions, there’s no global ordering — if your application needs strict ordering, route all related messages to the same partition (via keys).</li></ul><h3>5.3 Retention &amp; Cleanup</h3><ul><li>Kafka retains data for a configured time or size (retention.ms, retention.bytes).</li><li>Older segments are automatically deleted or compacted (if log compaction is enabled for the topic).</li></ul><h3>6. Scaling &amp; Fault Tolerance</h3><ul><li><strong>Horizontal Scaling</strong>: Add more brokers and increase partition count to spread load.</li><li><strong>Consumer Groups</strong>: Add more consumers to the same group to parallelize processing.</li><li><strong>Controller Election</strong>: In ZooKeeper mode, Kafka elects one broker as controller; in KRaft mode, controller duties can be shared across nodes.</li></ul><h3>7. Real-World Use Cases</h3><ol><li><strong>Activity Tracking</strong>: Clickstreams on websites.</li><li><strong>Log Aggregation</strong>: Centralize application logs for monitoring.</li><li><strong>Metrics &amp; Monitoring</strong>: Stream metrics into time-series databases.</li><li><strong>Event Sourcing</strong>: Store state changes as a sequence of events.</li><li><strong>Stream Processing</strong>: Connect with tools like Kafka Streams or Apache Flink to transform data on the fly.</li></ol><h3>8. Best Practices</h3><ul><li><strong>Monitor Lag</strong>: Track consumer offsets vs latest partition offsets to detect slow consumers.</li><li><strong>Tune Partitions</strong>: Balance between parallelism (more partitions) and overhead (network, I/O).</li><li><strong>Secure Your Cluster</strong>: Enable TLS encryption and SASL authentication.</li><li><strong>Use Log Compaction</strong> for topics that represent a changelog (e.g., latest state per key).</li><li><strong>Isolate Workloads</strong>: Separate critical real-time pipelines into dedicated clusters or tenants.</li></ul><h3>Conclusion</h3><p>Kafka transforms how systems communicate and process data by treating streams as a first-class citizen. Once you grasp its core abstractions — brokers, topics, partitions, producers, and consumers — you can architect robust, scalable, and real-time data pipelines. Start small with Docker and Python, get comfortable with basic produce/consume loops, then evolve into multi-node clusters, secure deployments, and complex stream-processing topologies. Happy streaming!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f38cfe297a56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Directory table in snowflake (Where are they useful?)]]></title>
            <link>https://shivharibaral.medium.com/directory-table-in-snowflake-where-are-they-useful-0a032626f5e4?source=rss-be47f291f8d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a032626f5e4</guid>
            <dc:creator><![CDATA[Shiv Hari Baral]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 07:58:11 GMT</pubDate>
            <atom:updated>2025-03-05T07:58:11.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YpX4ahBGm5ScYcee8hltxQ.jpeg" /></figure><p>Directory tables in Snowflake provide a powerful way to work with unstructured data by storing and exposing file-level metadata from external stages. A directory table is an implicit object layered on a stage (rather than a standalone database object) and functions much like an external table by storing file-level metadata about the files on that stage. Note that directory tables do not have their own grantable privileges.</p><p>Directory tables are supported on both external stages (e.g., cloud storage) and internal stages (Snowflake-managed). You can define a directory table either when creating a stage with CREATE STAGE or afterward with ALTER STAGE. Here’s a comprehensive look at when, where, and why they are useful, along with concrete implementation examples.</p><h3>When to Use Directory Tables</h3><ul><li><strong>Unstructured Data Ingestion</strong>:<br>When you have unstructured files (e.g., images, PDFs, videos) stored externally in cloud storage, directory tables allow you to list and manage these files without loading the file content into Snowflake.</li><li><strong>Metadata Extraction and File Management</strong>:<br>Use directory tables to query metadata such as file names, sizes, timestamps, and URLs. This is particularly useful if you need to build data processing pipelines or manage file workflows.</li><li><strong>Integration with Processing Pipelines</strong>:<br>When building automated pipelines (for example, using Snowpark or external functions), directory tables help you keep track of new or changed files so you can trigger processing jobs accordingly.</li></ul><h3>Where to Use Directory Tables</h3><ul><li><strong>On External Stages</strong>:<br>Directory tables are layered on external stages that point to cloud storage locations (e.g., AWS S3, Azure Blob Storage, or GCP Storage). They can also be used on internal stages in Snowflake.</li><li><strong>Within Data Pipelines</strong>:<br>Directory tables can serve as the starting point for ETL/ELT processes that extract file metadata and later join that metadata with structured data in Snowflake tables.</li><li><strong>In File Monitoring and Auditing</strong>:<br>They are useful in scenarios where you need to regularly audit or monitor files, such as verifying that new data files have arrived or checking for file changes over time.</li></ul><h4>Billing Considerations</h4><ul><li><strong>Automatic Refresh Overhead</strong>:<br>Event notifications for automatically refreshing directory table metadata incur charges that scale with the number of files added to your cloud storage. These charges appear as Snowpipe fees on your billing statement. You can monitor these costs by querying the PIPE_USAGE_HISTORY function or viewing the Account Usage PIPE_USAGE_HISTORY view.</li><li><strong>Manual Refresh Overhead</strong>:<br>Refreshing directory table metadata manually using ALTER STAGE ... REFRESH also incurs a minor maintenance charge under the standard cloud services billing model. However, these manual refresh costs are not displayed in the PIPE_USAGE_HISTORY view.</li><li><strong>Usage History Monitoring</strong>:<br>Users with the ACCOUNTADMIN role or roles with the global MONITOR USAGE privilege can query the AUTO_REFRESH_REGISTRATION_HISTORY table function to review the history of file registrations and the credits charged for these operations.</li></ul><h3>1. Set Up Your Role</h3><pre>USE ROLE ACCOUNTADMIN;</pre><p><strong>Explanation:</strong><br> You start by switching to the ACCOUNTADMIN role. This role has the necessary privileges to create and manage storage integrations, file formats, stages, and views in Snowflake.</p><h3>2. Create a Storage Integration</h3><pre>CREATE STORAGE INTEGRATION s3_int_AWS<br>  TYPE = EXTERNAL_STAGE<br>  STORAGE_PROVIDER = &#39;S3&#39;<br>  ENABLED = TRUE<br>  STORAGE_AWS_ROLE_ARN = &#39;arn:aws:iam::2025:role/snowflake-role&#39;<br>  STORAGE_ALLOWED_LOCATIONS = (&#39;s3://snowflake-aws-buckets/snowflake-directory-tables/&#39;);</pre><p><strong>Explanation:</strong></p><ul><li><strong>Storage Integration</strong>: This command creates a storage integration named s3_int_AWS.</li><li><strong>TYPE = EXTERNAL_STAGE</strong>: Specifies that this integration is used for external stages.</li><li><strong>STORAGE_PROVIDER = ‘S3’</strong>: Indicates that the external stage will use AWS S3.</li><li><strong>STORAGE_AWS_ROLE_ARN</strong>: Provides the ARN for the AWS IAM role that Snowflake will use to access the S3 bucket.</li><li><strong>STORAGE_ALLOWED_LOCATIONS</strong>: Limits access to the specified S3 bucket and folder.</li><li>This integration securely manages authentication and permissions, so you don’t need to embed sensitive credentials in your SQL scripts.</li></ul><p>After creation, you can verify it with:</p><pre>SHOW STORAGE INTEGRATIONS;<br>DESC INTEGRATION s3_int_AWS;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45b9erX6CKwuxZz7CRjAvg.png" /></figure><h3>3. Validate the Storage Integration</h3><pre>SELECT<br>  SYSTEM$VALIDATE_STORAGE_INTEGRATION(<br>    &#39;S3_INT_AWS&#39;,  <br>    &#39;s3://snowflake-aws-buckets/snowflake-directory-tables/&#39;,           <br>    &#39;img2.jpg&#39;,    <br>    &#39;all&#39;<br>  );</pre><p><strong>Explanation:</strong></p><ul><li>This function tests whether the storage integration S3_INT_AWS can access a specified file (img2.jpg) in the S3 bucket.</li><li>It checks the integration against the allowed location and runs all available validations.</li><li>This step is useful for troubleshooting, ensuring that your integration is set up correctly before moving on to create stages or load data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H0XEGamPCyrpDreH1CzRFw.png" /></figure><h3>4. Create a File Format</h3><pre>CREATE OR REPLACE FILE FORMAT my_csv_format<br>  TYPE = &#39;CSV&#39;<br>  FIELD_DELIMITER = &#39;,&#39;<br>  SKIP_HEADER = 0;</pre><p><strong>Explanation:</strong></p><ul><li>Even though you’re working with unstructured data like JPEG images, a file format must be defined when creating an external stage.</li><li>Here, a CSV format is used as a placeholder since the file format settings are irrelevant when you’re not parsing structured data.</li><li>You can verify its properties with:</li></ul><pre>DESC FILE FORMAT my_csv_format;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-M_hgKA9gRyFnxX0uR2yUw.png" /></figure><h3>5. Create an External Stage with Directory Support</h3><pre>CREATE STAGE my_s3_stage<br>  STORAGE_INTEGRATION = s3_int_AWS<br>  URL = &#39;s3://snowflake-aws-buckets/snowflake-directory-tables/&#39;<br>  DIRECTORY = (ENABLE = TRUE)<br>  FILE_FORMAT = my_csv_format;</pre><p><strong>Explanation:</strong></p><ul><li><strong>External Stage</strong>: This command creates a stage named my_s3_stage pointing to your S3 bucket.</li><li><strong>STORAGE_INTEGRATION</strong>: Uses the previously created integration for secure access.</li><li><strong>URL</strong>: Directs to the bucket and folder containing your unstructured files (e.g., JPEG images).</li><li><strong>DIRECTORY = (ENABLE = TRUE)</strong>: <strong>Enables directory table functionality. This allows Snowflake to automatically detect file metadata (such as file names, sizes, and timestamps) from the folder structure.</strong></li><li><strong>FILE_FORMAT</strong>: Associates the placeholder file format with the stage.</li><li>You can inspect the stage using:</li></ul><pre>DESC STAGE my_s3_stage;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1bib3nVfxGSGQ5ia9aR-w.png" /></figure><h3>6. Query the Directory Table for File Metadata</h3><pre>SELECT *<br>FROM DIRECTORY(@my_s3_stage);</pre><p><strong>Explanation:</strong></p><ul><li>This query returns a list of files in the S3 bucket along with metadata such as file names, sizes, and last-modified timestamps.</li><li>It’s an effective way to verify that your stage is correctly configured and that Snowflake is capturing the file-level metadata.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcvIdC31hLypXJDP6hBpCg.png" /></figure><p>This step-by-step setup not only facilitates the management of unstructured data (like JPEG images) in Snowflake but also demonstrates best practices for securely connecting to cloud storage and leveraging Snowflake’s powerful metadata querying capabilities.</p><p><strong>References:</strong></p><p><a href="https://docs.snowflake.com/en/user-guide/data-load-dirtables">https://docs.snowflake.com/en/user-guide/data-load-dirtables</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a032626f5e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streams : Change data capture in snowflake(Part 2)]]></title>
            <link>https://shivharibaral.medium.com/streams-change-data-capture-in-snowflake-part-2-692834d0c50a?source=rss-be47f291f8d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/692834d0c50a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[snowflake-data-cloud]]></category>
            <category><![CDATA[snowflake-developer]]></category>
            <dc:creator><![CDATA[Shiv Hari Baral]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 07:25:05 GMT</pubDate>
            <atom:updated>2025-03-04T07:25:05.812Z</atom:updated>
            <content:encoded><![CDATA[<h3>Streams : Change data capture in snowflake(Part 2)</h3><p>Please refer to part1 of this article for introduction.</p><p><a href="https://shivharibaral.medium.com/streams-and-tasks-change-data-capture-in-snowflake-part-1-153f7c9812d1">https://shivharibaral.medium.com/streams-and-tasks-change-data-capture-in-snowflake-part-1-153f7c9812d1</a></p><p>Below is the practical implementation of streams.</p><h3>1. Set the Active Role</h3><pre>USE ROLE SYSADMIN;</pre><p><em>Explanation:</em><br> This command sets your current role to SYSADMIN, ensuring you have the necessary privileges to create and manage warehouses, databases, schemas, tables, and streams.</p><h3>2. Create a Compute Warehouse</h3><pre>CREATE OR REPLACE WAREHOUSE DEMO_WH<br>  WAREHOUSE_SIZE = &#39;SMALL&#39;<br>  AUTO_SUSPEND = 60<br>  AUTO_RESUME = TRUE<br>  INITIALLY_SUSPENDED = TRUE;</pre><p><em>Explanation:</em><br> This statement creates (or replaces) a warehouse named DEMO_WH with the following settings:</p><ul><li><strong>SMALL</strong> size for cost efficiency.</li><li><strong>AUTO_SUSPEND:</strong> The warehouse will automatically suspend after 60 seconds of inactivity.</li><li><strong>AUTO_RESUME:</strong> It will automatically resume when a query is submitted.</li><li><strong>INITIALLY_SUSPENDED:</strong> The warehouse starts in a suspended state.</li></ul><h3>3. Create a Database and Schema</h3><pre>CREATE OR REPLACE DATABASE DEMO_CDC;<br>CREATE OR REPLACE SCHEMA DEMO_CDC_SCHEMA;</pre><p><em>Explanation:</em><br> These commands create (or replace) a database called DEMO_CDC and a schema within that database named DEMO_CDC_SCHEMA. This organizes your objects for change data capture (CDC) demonstration.</p><h3>4. Create a Dummy Table</h3><pre>CREATE OR REPLACE TABLE dummy_data (<br>    id INTEGER AUTOINCREMENT,<br>    name STRING,<br>    age INTEGER,<br>    active BOOLEAN,<br>    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>);</pre><p><em>Explanation:</em><br> A table named dummy_data is created with various data types:</p><ul><li><strong>id:</strong> An auto-incremented integer serving as the unique identifier.</li><li><strong>name:</strong> A string column for names.</li><li><strong>age:</strong> An integer for age values.</li><li><strong>active:</strong> A boolean indicating active status.</li><li><strong>created_at:</strong> A timestamp column automatically set to the current time upon row creation.</li></ul><h3>5. Insert Sample Data into the Table</h3><pre>INSERT INTO dummy_data (name, age, active)<br>VALUES <br>  (&#39;Alice&#39;, 30, TRUE),<br>  (&#39;Bob&#39;, 45, FALSE),<br>  (&#39;Charlie&#39;, 28, TRUE),<br>  (&#39;Diana&#39;, 33, TRUE),<br>  (&#39;Ethan&#39;, 40, FALSE),<br>  (&#39;Fiona&#39;, 22, TRUE);</pre><p><em>Explanation:</em><br> Six sample rows are inserted into dummy_data with various names, ages, and active statuses to provide an initial dataset.</p><h3>6. Verify the Insertions</h3><pre>SELECT * FROM dummy_data;</pre><p><em>Explanation:</em><br> This query retrieves all records from dummy_data so you can confirm that the data was successfully inserted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RRh4dly5l09REa7cQFxNA.png" /></figure><h3>7. Create Streams on the Table</h3><pre>CREATE OR REPLACE STREAM dummy_data_stream_A ON TABLE dummy_data;<br>CREATE OR REPLACE STREAM dummy_data_stream_B ON TABLE dummy_data;</pre><p><em>Explanation:</em><br> Two streams, dummy_data_stream_A and dummy_data_stream_B, are created to track all changes (inserts, updates, and deletes) made to the dummy_data table. These streams will capture the delta between the current data state and subsequent changes.</p><h3>8. Query the Streams Initially</h3><pre>SELECT * FROM dummy_data_stream_A;<br>SELECT * FROM dummy_data_stream_B;</pre><p><em>Explanation:</em><br> These queries check the current state of the streams. Since no new changes have occurred after the streams were created, they might show either no records or an initial snapshot, depending on how the stream handles the initial state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUNPC4RHPRQCj0by34BQ-w.png" /></figure><h3>9. Insert Additional Rows</h3><pre>INSERT INTO dummy_data (name, age, active)<br>VALUES <br>  (&#39;Diana&#39;, 33, TRUE),<br>  (&#39;Ethan&#39;, 40, FALSE),<br>  (&#39;Fiona&#39;, 22, TRUE);</pre><p><em>Explanation:</em><br> Three additional rows are inserted into dummy_data. These new DML operations will be captured by the streams, recording the new changes made after the streams were initially created.</p><h3>10. Query the Streams After Inserting Data</h3><pre>SELECT * FROM dummy_data_stream_A;<br>SELECT * FROM dummy_data_stream_B;</pre><p><em>Explanation:</em><br> Re-querying the streams shows the three newly inserted rows. Both streams now capture the delta created by these additional inserts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvtzIVwtP9BJ6Q17Mmgclw.png" /></figure><h3>11. Create a Third Stream</h3><pre>CREATE OR REPLACE STREAM dummy_data_stream_C ON TABLE dummy_data;<br>SELECT * FROM dummy_data_stream_C;</pre><p><em>Explanation:</em><br> A third stream (dummy_data_stream_C) is created on the dummy_data table to demonstrate that you can have multiple streams on a single table. Querying it immediately shows the captured change data up to the moment of its creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTh3xHZa4j0acPkqgLuXNA.png" /></figure><h3>12. Insert Another Row</h3><pre>INSERT INTO dummy_data (name, age, active)<br>VALUES <br>  (&#39;Ayan&#39;, 22, TRUE);</pre><p><em>Explanation:</em><br> A new row is inserted into dummy_data. This operation will be recorded as a new change in the streams.</p><h3>13. Query Stream C After New Insertion</h3><pre>SELECT * FROM dummy_data_stream_C;</pre><p><em>Explanation:</em><br> This query retrieves the changes captured by dummy_data_stream_C, including the recently inserted row for &#39;Ayan&#39;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zo0WTAJGC3mO-Pi4dR07hw.png" /></figure><h3>14. Check the results of all streams</h3><p>Here is why stream A , stream B and stream C result may be different:</p><ol><li><strong>Stream A and Stream B</strong></li></ol><ul><li><strong>Created earlier</strong>: They began tracking from an earlier point in time.</li><li>As a result, they both captured <strong>all</strong> the insertions you made after their creation:</li><li>Ayan (ID = 101)</li><li>Diana (ID = 7)</li><li>Ethan (ID = 8)</li><li>Fiona (ID = 9)</li><li>When you query these streams, they still show those inserted rows because their offsets haven’t been advanced by a DML consumption operation.</li></ul><ol><li><strong>Stream C</strong></li></ol><ul><li><strong>Created later</strong>: It started tracking changes from the moment it was created, which was after you had already inserted some rows (Diana, Ethan, Fiona).</li><li>Therefore, <strong>Stream C</strong> only shows the <strong>newest</strong> insertion (Ayan with ID = 101) that happened <strong>after</strong> it was created.</li><li>The earlier inserts (Diana, Ethan, Fiona) do not appear because they happened before Stream C existed.</li></ul><ol><li><strong>Why Queries Show Different Rows?</strong></li></ol><ul><li>A Snowflake stream’s “view” of changes begins at its creation time (the offset). Anything inserted before the stream existed is not tracked by that stream.</li><li>Unless you consume the stream (using a DML statement like INSERT INTO some_table SELECT * FROM dummy_data_stream_X), the stream’s offset does not move forward and the same changes remain visible when you query it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQ3mdOhKgn_STT2V5vQgfA.png" /><figcaption>Stream A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F0FNVam3yHUvgeS9tMd-YA.png" /><figcaption>Stream B</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwZel3j-j3LDK-zS7QpF8g.png" /><figcaption>Stream C</figcaption></figure><h3>15. Delete a Row (First Deletion)</h3><pre>DELETE FROM dummy_data WHERE ID = 101;</pre><p><em>Explanation:</em><br> A deletion is performed on a row with an ID of 101. This action is captured as a delete event in the stream(s), marking the row as removed.</p><h3>16. Verify the Deletion in Stream C</h3><pre>SELECT * FROM dummy_data_stream_C;</pre><p><em>Explanation:</em></p><p>A <strong>standard (delta) stream</strong> captures inserts, updates, and deletes as <strong>net changes</strong> between two offsets. If a row is <strong>inserted</strong> and then <strong>deleted</strong> <strong>before</strong> the stream’s offset advances (i.e., before the stream is consumed in a DML statement), the net effect is that the row never existed from the stream’s point of view. Therefore, querying the stream shows “no results” for that row.A stream’s offset only advances when you consume it in a DML transaction, such as</p><pre>-- Create or replace the target table.<br>CREATE OR REPLACE TABLE ANOTHER_TABLE (<br>    id INTEGER,<br>    name STRING,<br>    age INTEGER,<br>    active BOOLEAN,<br>    created_at TIMESTAMP,<br>    METADATA$ACTION STRING,<br>    METADATA$ISUPDATE BOOLEAN,<br>    METADATA$ROW_ID STRING<br>);<br><br>-- Consume the stream data, inserting into the new table.<br>INSERT INTO ANOTHER_TABLE<br>SELECT <br>    id,<br>    name,<br>    age,<br>    active,<br>    created_at,<br>    METADATA$ACTION,<br>    METADATA$ISUPDATE,<br>    METADATA$ROW_ID<br>FROM dummy_data_stream_C;</pre><p>or a similar operation (CTAS, COPY INTO, etc.). Simply running a SELECT on the stream does <strong>not</strong> advance the offset. Until a DML statement consumes the stream, all changes since the last offset are treated as a single batch of net changes.<br> Querying the stream C after the deletion shows the delete event for the row with ID = 301.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4IrnADYge2RPrCDeCa6KYQ.png" /></figure><h3>17. Update a Row and Check the Changes in Stream A</h3><pre>UPDATE dummy_data<br>SET Name = &#39;Fiona&#39; WHERE ID = 101;<br>SELECT * FROM dummy_data_stream_A;<br>SELECT * FROM dummy_data_stream_C;</pre><p><em>Explanation:</em><br> This update changes the Name field for the row with ID = 101 to &#39;Fiona&#39;. In streams, updates are typically captured as a pair of events—a delete for the old value and an insert for the new value. The query on dummy_data_stream_C reflects this change by showing the update events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMK6Kj3a8eLkZBY9cIi2lA.png" /><figcaption>Stream A</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GTcWmGd0D0_XiXThvLbBHw.png" /><figcaption>Stream C</figcaption></figure><h3>18. How Snowflake Streams Represent an UPDATE ?</h3><p>A <strong>standard (delta) stream</strong> treats an update as a pair of changes:</p><ol><li>A <strong>DELETE</strong> of the old row (with METADATA$ISUPDATE = TRUE).</li><li>An <strong>INSERT</strong> of the new row (also with METADATA$ISUPDATE = TRUE).</li></ol><p>When you query the stream <strong>before</strong> consuming (i.e., advancing the offset), you’ll see both the DELETE and INSERT records if the updated row actually changed. If you only see one row, that usually means:</p><ul><li>The stream was created <strong>after</strong> the old version of the row existed, so it only captured the “new” state.</li><li>Or the net effect in the same offset “cancels out” the old record (e.g., if the name was updated to the same value, sometimes it’s treated as no net change).</li></ul><p><strong>Useful commands to check streams:</strong></p><p><strong>SHOW STREAMS;<br>DESCRIBE STREAM &lt;stream_name&gt;;</strong></p><p>Each of these queries plays a role in demonstrating how streams in Snowflake track and capture data changes over time, making them a powerful tool for building change data capture (CDC) pipelines.</p><p><strong>References:</strong></p><p><a href="https://docs.snowflake.com/en/user-guide/streams-intro">https://docs.snowflake.com/en/user-guide/streams-intro</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=692834d0c50a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streams : Change data capture in snowflake(Part 1)]]></title>
            <link>https://shivharibaral.medium.com/streams-and-tasks-change-data-capture-in-snowflake-part-1-153f7c9812d1?source=rss-be47f291f8d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/153f7c9812d1</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[snowflake-developer]]></category>
            <category><![CDATA[change-data-capture]]></category>
            <dc:creator><![CDATA[Shiv Hari Baral]]></dc:creator>
            <pubDate>Tue, 04 Mar 2025 05:50:05 GMT</pubDate>
            <atom:updated>2025-03-04T06:22:53.235Z</atom:updated>
            <content:encoded><![CDATA[<p>Snowflake Streams are incredibly useful for capturing incremental changes to data in real time without needing to perform expensive, full-table scans. Snowflake streams capture all DML changes — such as inserts, updates, and deletes — along with metadata, enabling change data capture (CDC). A stream tracks row-level changes between two points in time, making a “change table” available for transactional queries and consumption. Streams can be created on various objects, including standard (and shared) tables, views (even secure ones), directory tables, dynamic tables, Apache Iceberg™ tables (with some limitations), event tables, and external tables. Lets discuss some of the use case of streams before diving deep into streams</p><ol><li><strong>Real-Time Data Integration:</strong><br>In environments like e-commerce or financial services, new transactions or orders are constantly added. A stream on an orders or transactions table can capture these changes as they happen. Then, using Snowflake Tasks, you can automatically process and merge these incremental updates into your reporting or analytics tables, ensuring that your dashboards and business intelligence tools are always up-to-date.</li></ol><ul><li><strong>Change Data Capture (CDC) for ETL Pipelines:</strong><br>Streams provide a lightweight change data capture mechanism. For example, if you maintain a large customer database, you might want to capture just the changes (inserts, updates, deletes) and apply them to a downstream system (like a data warehouse or a data lake) rather than reloading the entire dataset every time. This can significantly reduce processing time and resource usage.</li><li><strong>Auditing and Data Lineage:</strong><br>Streams help track how data evolves over time. By capturing changes to a table, you can maintain an audit log that shows exactly what data was modified, when, and by whom (if you have that metadata). This is critical for compliance and troubleshooting in regulated industries.</li><li><strong>Event-Driven Architectures:</strong><br>In modern applications, events (such as a user placing an order or updating their profile) trigger downstream processes. Streams can serve as the trigger source — when a new event (insert) occurs in a table, the stream can feed that event into an automated workflow that processes the data and triggers notifications or further business logic.</li></ul><h4><strong>How streams work?</strong></h4><p>When a stream is created, it captures an initial snapshot of every row in its source (a table, external table, or view) by setting an offset — essentially a timestamp that marks the current version of the data. From that point, the change tracking system records any DML changes, capturing both the before-and-after state of rows along with metadata about each change.</p><ul><li><strong>Snapshot &amp; Offset:</strong><br>The stream takes an initial snapshot and then records subsequent changes using the source’s current schema. Hidden metadata columns are added to the source to track these changes.</li><li><strong>Streams as Bookmarks:</strong><br>Think of a stream as a bookmark in a book — it marks a specific point in time and can be replaced or re-created at different times to capture change data.</li><li><strong>Table Versioning:</strong><br>Each committed transaction creates a new table version. A stream’s offset falls between these versions, so querying it returns changes from the version immediately after the offset up to the latest version.</li><li><strong>Data Consumption:</strong><br>The stream provides the minimal set of changes from its offset. Consuming change data in a DML transaction (like CTAS or COPY INTO) advances the offset. Simply querying the stream does not advance the offset.</li><li><strong>Repeatable Read Isolation:</strong><br>Within an explicit transaction, multiple queries against a stream will see the same consistent set of change records, ensuring stable read results.</li><li><strong>Stream Metadata &amp; Types:</strong><br>Streams return data in the shape of the source with additional metadata columns such as:</li><li><strong>METADATA$ACTION:</strong> The type of DML operation (INSERT, DELETE).</li><li><strong>METADATA$ISUPDATE:</strong> Indicates if a change was part of an update.</li><li><strong>METADATA$ROW_ID:</strong> A unique identifier for each row.</li></ul><p>Depending on the use case, streams can be:</p><ul><li><strong>Standard Streams:</strong> Track all DML changes (inserts, updates, deletes).</li><li><strong>Append-Only Streams:</strong> Capture only new row inserts.</li><li><strong>Insert-Only Streams:</strong> Similar to append-only but designed for Apache Iceberg™ or external tables.</li></ul><h3>Data Flow and Stream Lifecycle</h3><p>A standard stream tracks changes in a source table by capturing updates as they occur. Every time a DML statement consumes the stream’s content, the stream’s position (or offset) advances to reflect the next set of changes. This dynamic update is illustrated by diagrams showing how the stream’s content evolves alongside table versions.</p><figure><img alt="https://docs.snowflake.com/en/_images/data-pipeline-streams.png" src="https://cdn-images-1.medium.com/max/1024/1*bE0MrQzOuF28xOG5tWMSHg.png" /></figure><h3>Data Retention and Preventing Staleness</h3><p>A stream becomes <strong>stale</strong> when its offset falls outside the source table’s data retention period. Once stale, any unconsumed historical change records are lost. To avoid this:</p><ul><li><strong>Regular Consumption:</strong> Consume change records within the table’s retention period (or before the STALE_AFTER timestamp) using a DML statement.</li><li><strong>System Function:</strong> Use functions like SYSTEM$STREAM_HAS_DATA to ensure the stream remains active.</li><li><strong>Parameter Settings:</strong> Snowflake may temporarily extend the data retention period — up to a maximum defined by the MAX_DATA_EXTENSION_TIME_IN_DAYS parameter — to help prevent staleness. However, once change data is consumed, the retention period reverts to its default value.</li></ul><p>You can check the stream’s staleness status using commands like DESCRIBE STREAM or SHOW STREAMS, which provide a STALE_AFTER timestamp indicating when the stream is or will become stale. Be mindful that recreating a table (via CREATE OR REPLACE TABLE) or its underlying objects makes the associated stream stale.</p><h3>Handling Multiple Consumers</h3><p>Since a stream’s offset advances when consumed in a DML transaction, different consumers (tasks, scripts, etc.) won’t see the same change data if they share a single stream. It is best to create separate streams for each consumer to ensure that each one can access the full set of change records without interference.</p><h3>Streams on Views</h3><p>Streams can also be applied to views — including shared and secure views — but with some caveats:</p><ul><li><strong>Underlying Requirements:</strong> All underlying tables must be native tables with change tracking enabled.</li><li><strong>Supported Operations:</strong> Views must only use basic operations (projections, filters, inner/cross joins, UNION ALL). More complex operations like GROUP BY, DISTINCT, and correlated subqueries aren’t supported.</li><li><strong>Materialized Views:</strong> Currently, streams cannot track changes in materialized views.</li></ul><p>By understanding these key aspects — data flow, retention, staleness, consumer management, and view limitations — you can effectively leverage streams for continuous data capture and change tracking in your data pipelines.</p><p><strong>References:</strong></p><ul><li><a href="https://docs.snowflake.com/en/user-guide/streams-intro">Introduction to Streams | Snowflake Documentation</a></li><li><a href="https://www.amazon.com/Snowflake-Data-Engineering-Maja-Ferle/dp/1633436853">Snowflake Data Engineering</a></li></ul><p><a href="https://www.amazon.com/Snowflake-Definitive-Architecting-Designing-Deploying/dp/1098103823/ref=asc_df_1098103823?mcid=4fd9e988884030b6a265c9a3b00d81dd&amp;tag=hyprod-20&amp;linkCode=df0&amp;hvadid=693348626821&amp;hvpos=&amp;hvnetw=g&amp;hvrand=16352745881508984395&amp;hvpone=&amp;hvptwo=&amp;hvqmt=&amp;hvdev=c&amp;hvdvcmdl=&amp;hvlocint=&amp;hvlocphy=1026214&amp;hvtargid=pla-1644337159570&amp;psc=1">https://www.amazon.com/Snowflake-Definitive-Architecting-Designing-Deploying/dp/1098103823/ref=asc_df_1098103823?mcid=4fd9e988884030b6a265c9a3b00d81dd&amp;tag=hyprod-20&amp;linkCode=df0&amp;hvadid=693348626821&amp;hvpos=&amp;hvnetw=g&amp;hvrand=16352745881508984395&amp;hvpone=&amp;hvptwo=&amp;hvqmt=&amp;hvdev=c&amp;hvdvcmdl=&amp;hvlocint=&amp;hvlocphy=1026214&amp;hvtargid=pla-1644337159570&amp;psc=1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=153f7c9812d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Informed Search vs Uninformed search in AI]]></title>
            <link>https://shivharibaral.medium.com/informed-search-vs-uninformed-search-in-ai-802f95260304?source=rss-be47f291f8d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/802f95260304</guid>
            <category><![CDATA[search-algorithm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shiv Hari Baral]]></dc:creator>
            <pubDate>Sun, 11 Dec 2022 15:13:10 GMT</pubDate>
            <atom:updated>2022-12-11T15:13:10.271Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Informed Search vs Uninformed search in AI</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*auyXJG_Wqagfdkz96ZLzdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frEni0tA-iTHmQr1VNBF-A.jpeg" /><figcaption>Fig. Classification of search algorithms</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*lQYXZssxKAk-Zje-hxIiNw.png" /><figcaption>Fig. Time Complexity of Search Algorithm</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=802f95260304" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>