<?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 Agnibesh Banerjee on Medium]]></title>
        <description><![CDATA[Stories by Agnibesh Banerjee on Medium]]></description>
        <link>https://medium.com/@agnee008?source=rss-9a8762b15d90------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VrxM0lzIJTjnZCcalXiCZw.jpeg</url>
            <title>Stories by Agnibesh Banerjee on Medium</title>
            <link>https://medium.com/@agnee008?source=rss-9a8762b15d90------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 12:00:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@agnee008/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[I Built a System That Fixes AWS Incidents While I’m Still Reading the Alert]]></title>
            <link>https://medium.com/@agnee008/i-built-a-system-that-fixes-aws-incidents-while-im-still-reading-the-alert-26c77629cdf3?source=rss-9a8762b15d90------2</link>
            <guid isPermaLink="false">https://medium.com/p/26c77629cdf3</guid>
            <category><![CDATA[aws-cloudwatch]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Agnibesh Banerjee]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 12:26:22 GMT</pubDate>
            <atom:updated>2026-03-21T12:26:22.180Z</atom:updated>
            <content:encoded><![CDATA[<p>3 AM. Phone buzzes. Production is down.</p><p>I open my laptop, log into AWS, check CloudWatch, find the issue, apply the fix.</p><p>12 minutes. Feels like an hour. Users are frustrated. Someone is watching. Stress kicks in fast.</p><p>Then it hit me:</p><p>I do the same thing every single time.<br>So why am <em>I</em> the one doing it?</p><p>That’s when I built a system that doesn’t just alert me… it actually fixes the problem.</p><h3>What Happens Now at 3 AM</h3><p>When something breaks:</p><ul><li>The system detects the issue</li><li>Runs diagnostics automatically</li><li>Applies the right fix</li><li>Verifies the outcome</li><li>Notifies me it’s resolved</li></ul><p>I stay asleep.</p><p>Last month:</p><ul><li>14 incidents</li><li>11 auto-resolved</li><li>I only woke up for the 3 that actually needed me</li></ul><h3>The Problem with Manual Incident Response</h3><p>Every incident looks like this:</p><ol><li>Alert fires</li><li>You wake up</li><li>You check CloudWatch</li><li>You identify the issue</li><li>You run familiar commands</li><li>You apply the usual fix</li><li>You verify</li><li>You try to go back to sleep</li></ol><p>And most of the time, it’s predictable:</p><ul><li>DynamoDB throttling → increase capacity</li><li>Lambda timeout → increase memory</li><li>API Gateway 5xx → restart backends</li><li>S3 access issues → fix policies</li><li>RDS connections exhausted → kill queries</li></ul><p>You already know the problem.<br>You already know the fix.</p><p>So why are you in the middle?</p><h3>What I Built: Self-Healing Infrastructure</h3><p>An event-driven system that reacts to CloudWatch alarms.</p><p>When an alarm fires:</p><ol><li>A Lambda function receives the event</li><li>Identifies the incident type</li><li>Runs diagnostics</li><li>Executes a predefined playbook</li><li>Verifies the fix</li><li>Logs everything</li><li>Calls a human only if needed</li></ol><p>Think of it like a solid junior engineer handling routine issues while you sleep.</p><h3>The Core: Incident Detection</h3><pre>class IncidentResponder:<br>    &quot;&quot;&quot;<br>    Automated incident response system.<br>    Detects issues and applies fixes automatically.<br>    &quot;&quot;&quot;<br>    <br>    def __init__(self):<br>        self.cloudwatch = boto3.client(&#39;cloudwatch&#39;)<br>        self.dynamodb = boto3.client(&#39;dynamodb&#39;)<br>        self.lambda_client = boto3.client(&#39;lambda&#39;)<br>        self.ec2 = boto3.client(&#39;ec2&#39;)<br>        self.rds = boto3.client(&#39;rds&#39;)<br>        <br>        self.playbooks = self._load_playbooks()<br>    <br>    def handle_alarm(self, alarm_event: Dict) -&gt; Dict:<br>        alarm_name = alarm_event[&#39;AlarmName&#39;]<br>        metric_name = alarm_event[&#39;Trigger&#39;][&#39;MetricName&#39;]<br>        namespace = alarm_event[&#39;Trigger&#39;][&#39;Namespace&#39;]<br>        dimensions = alarm_event[&#39;Trigger&#39;][&#39;Dimensions&#39;]<br>        <br>        incident = self._identify_incident(<br>            alarm_name, metric_name, namespace, dimensions<br>        )<br>        <br>        if not incident:<br>            return {<br>                &#39;incident_type&#39;: &#39;unknown&#39;,<br>                &#39;success&#39;: False,<br>                &#39;human_required&#39;: True<br>            }<br>        <br>        playbook = self.playbooks.get(incident[&#39;type&#39;])<br>        <br>        if not playbook:<br>            return {<br>                &#39;incident_type&#39;: incident[&#39;type&#39;],<br>                &#39;success&#39;: False,<br>                &#39;human_required&#39;: True<br>            }<br>        <br>        return self._execute_playbook(playbook, incident)</pre><h3>Incident Recognition</h3><p>Simple pattern matching:</p><pre>def _identify_incident(self, alarm_name, metric_name, namespace, dimensions):<br>    <br>    if namespace == &#39;AWS/DynamoDB&#39; and &#39;Throttle&#39; in metric_name:<br>        return {&#39;type&#39;: &#39;dynamodb_throttle&#39;}<br>    if namespace == &#39;AWS/Lambda&#39; and &#39;Duration&#39; in metric_name:<br>        return {&#39;type&#39;: &#39;lambda_timeout&#39;}<br>    if namespace == &#39;AWS/ApiGateway&#39; and &#39;5XXError&#39; in metric_name:<br>        return {&#39;type&#39;: &#39;api_gateway_5xx&#39;}<br>    if namespace == &#39;AWS/RDS&#39; and &#39;DatabaseConnections&#39; in metric_name:<br>        return {&#39;type&#39;: &#39;rds_connection_exhaustion&#39;}<br>    return None</pre><h3>The Playbook System</h3><p>Each issue has a defined response:</p><pre>def _load_playbooks(self):<br>    return {<br>        &#39;dynamodb_throttle&#39;: {<br>            &#39;diagnostics&#39;: [self._check_dynamodb_metrics],<br>            &#39;fixes&#39;: [self._increase_dynamodb_capacity],<br>            &#39;verification&#39;: [self._verify_throttling_stopped],<br>            &#39;auto_fix_enabled&#39;: True<br>        },<br>        <br>        &#39;lambda_timeout&#39;: {<br>            &#39;diagnostics&#39;: [self._check_lambda_metrics],<br>            &#39;fixes&#39;: [<br>                self._increase_lambda_memory,<br>                self._increase_lambda_timeout<br>            ],<br>            &#39;verification&#39;: [self._verify_lambda_success_rate],<br>            &#39;auto_fix_enabled&#39;: True<br>        }<br>    }</pre><h3>Execution Flow</h3><pre>def _execute_playbook(self, playbook, incident):<br>    # Diagnostics<br>    diagnostics = {}<br>    for func in playbook[&#39;diagnostics&#39;]:<br>        diagnostics[func.__name__] = func()<br>    # Fixes<br>    results = []<br>    for func in playbook[&#39;fixes&#39;]:<br>        results.append(func())<br>    # Verification<br>    verified = all(v()[&#39;success&#39;] for v in playbook[&#39;verification&#39;])<br>    return {<br>        &#39;success&#39;: verified,<br>        &#39;human_required&#39;: not verified<br>    }</pre><h3>Example: DynamoDB Throttling Fix</h3><pre>def _increase_dynamodb_capacity(self, table_name, diagnostics):<br>    current_read = diagnostics[&#39;read&#39;]<br>    current_write = diagnostics[&#39;write&#39;]<br>    new_read = int(current_read * 1.5)<br>    new_write = int(current_write * 1.5)<br>    self.dynamodb.update_table(<br>        TableName=table_name,<br>        ProvisionedThroughput={<br>            &#39;ReadCapacityUnits&#39;: new_read,<br>            &#39;WriteCapacityUnits&#39;: new_write<br>        }<br>    )<br>    return {&#39;action&#39;: &#39;capacity_increased&#39;}</pre><h3>Safety Rails</h3><p>Automation without control is dangerous.</p><pre>class SafetyChecker:<br>  def can_apply_fix(self, resource):<br>        recent_fixes = self._get_recent_fixes(resource)<br>        if len(recent_fixes) &gt;= 3:<br>            return False<br>        if self._in_maintenance_window():<br>            return False<br>        if self._is_protected(resource):<br>            return False<br>        return True</pre><h3>Notifications</h3><p>Only escalate when needed:</p><ul><li>Success → Teams message</li><li>Failure → page human</li><li>Unknown → page human immediately</li></ul><h3>Real Results (After 3 Months)</h3><p><strong>Before:</strong></p><ul><li>47 incidents/month</li><li>Woken up every time</li><li>12 min average response</li><li>5.4 hrs sleep</li><li>Frequent mistakes</li></ul><p><strong>After:</strong></p><ul><li>42 incidents/month</li><li>31 auto-resolved</li><li>11 required intervention</li><li>2 min auto-resolution</li><li>7.1 hrs sleep</li><li>Zero mistakes</li></ul><p><strong>Auto-resolution rate: 74%</strong></p><h3>The Incidents That Still Needed Me</h3><p>All edge cases:</p><ul><li>Security issues</li><li>AWS-level failures</li><li>Code bugs</li><li>Race conditions</li></ul><p>The system handled the routine. I handled the judgment calls.</p><h3>What I Learned</h3><p><strong>1. Start with diagnostics only</strong><br>Let it observe before it acts.</p><p><strong>2. Automate one playbook at a time</strong><br>Build confidence gradually.</p><p><strong>3. Safety is everything</strong><br>Rate limits, approvals, protected resources.</p><p><strong>4. Log everything</strong><br>You need an audit trail.</p><p><strong>5. Always verify fixes</strong><br>Never assume success.</p><h3>Common Pitfalls</h3><ul><li>Don’t automate destructive actions</li><li>Don’t overcorrect (I started with 2x scaling, bad idea)</li><li>Test in dev first</li><li>Add a global kill switch</li><li>Review logs regularly</li></ul><h3>The Shift That Made It Work</h3><p>I stopped thinking of it as a script.</p><p>And started thinking of it as a junior engineer.</p><p>Not:</p><blockquote><em>“Increase DynamoDB capacity”</em></blockquote><p>But:</p><blockquote><em>“Diagnose, fix, and verify autonomously”</em></blockquote><p>That mindset changes everything.</p><h3>FAQs</h3><p><strong>What if it makes things worse?</strong><br>Safety limits prevent runaway fixes. In 3 months, zero regressions.</p><p><strong>What about compliance?</strong><br>Everything is logged. Full audit trail.</p><p><strong>What if AWS itself is down?</strong><br>Those incidents are escalated immediately.</p><p><strong>Cost?</strong><br>~£15/month. Saves ~30+ hours of engineering time.</p><h3>Your Turn</h3><p>You can build this in a weekend:</p><ol><li>Deploy a Lambda handler</li><li>Create one playbook (start with DynamoDB throttling)</li><li>Run in read-only mode</li><li>Observe for a week</li><li>Enable auto-fix</li><li>Expand gradually</li></ol><h3>The 3 AM Test</h3><p><strong>Before:</strong><br>Phone buzzes. You fix the same issue again. 12 minutes gone.</p><p><strong>After:</strong><br>You wake up. Check Teams.<br>“Auto-resolved at 3:17 AM.”</p><p>That’s the difference.</p><h3>What’s Next</h3><p>I’m working on:</p><ul><li>Predictive alerts (before incidents happen)</li><li>Better verification using business metrics</li><li>Automatic rollback if fixes fail</li><li>Learning from manual interventions</li></ul><p>Goal: 95% auto-resolution.</p><h3>Final Thought</h3><p>You already know your common incidents.<br>You already know how to fix them.</p><p>Automate that.</p><p>Your future self at 3 AM will be grateful :)</p><h4>Grab the full code → <a href="https://github.com/agnee008/self-healing-poc/tree/main">AWS Self Healing (Phase-1)</a></h4><p><em>*About the Author: Agnibes Banerjee is a Lead AWS Data Engineer with 8 years of experience building scalable data solutions. Previously at Dyson (UK), IBM (UK), and currently at Barclays (India), specializing in real-time streaming architectures and event-driven systems.*</em></p><p><strong>Connect:</strong></p><p>- <a href="https://linkedin.com/in/agnibeshbanerjee">LinkedIn</a></p><p>- <a href="https://github.com/agnee008">GitHub</a></p><p>- <a href="https://medium.com/@agnee008">Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26c77629cdf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built a Tool That Auto-Tags All My AWS Resources (And It Saved Me During an Audit)]]></title>
            <link>https://medium.com/@agnee008/i-built-a-tool-that-auto-tags-all-my-aws-resources-and-it-saved-me-during-an-audit-00cb6d77b172?source=rss-9a8762b15d90------2</link>
            <guid isPermaLink="false">https://medium.com/p/00cb6d77b172</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Agnibesh Banerjee]]></dc:creator>
            <pubDate>Sat, 07 Mar 2026 08:40:34 GMT</pubDate>
            <atom:updated>2026-03-07T08:40:34.208Z</atom:updated>
            <content:encoded><![CDATA[<p>Three months ago, our finance team asked a simple question:</p><blockquote><strong><em>“Which team owns this £12,000/month DynamoDB table?”</em></strong></blockquote><p>Nobody knew.</p><p>We had <strong>847 AWS resources across 6 accounts</strong>. Maybe <strong>30% were tagged</strong>.</p><p>The rest? Mystery meat.</p><p>Then compliance scheduled an audit. They wanted to know:</p><ul><li>Who owned each resource</li><li>Which project it belonged to</li><li>Why it existed</li></ul><p>I had <strong>two weeks</strong> to tag everything.</p><p>Manually tagging would take <strong>months</strong>.</p><p>So I built a tool that does it automatically.</p><ul><li>Built in <strong>two days</strong></li><li>Saved the <strong>audit</strong></li><li>Now runs <strong>daily</strong></li></ul><p>Here’s how it works and why you probably need it too.</p><h3>The Tagging Problem Nobody Talks About</h3><p>Everyone knows you <strong>should tag AWS resources</strong>.</p><p>Almost nobody does it consistently.</p><h3>Why tagging fails</h3><ul><li>Developers forget. They’re focused on shipping code.</li><li>Manual tagging is tedious.</li><li>Tags drift when someone accidentally deletes them.</li><li>AWS doesn’t enforce tagging by default.</li><li>Every AWS service has different tagging APIs.</li></ul><p>The result: a tagging mess that costs real money.</p><p>Without tags you can’t:</p><ul><li>Know who owns a resource</li><li>Split costs by team or project</li><li>Find orphaned resources</li><li>Pass compliance audits</li><li>Automatically shut down dev resources</li></ul><h3>What I Built</h3><p>An automated tagging system that:</p><ol><li>Scans <strong>all AWS resources across all services</strong></li><li>Infers tags from <strong>naming patterns</strong></li><li>Auto-tags resources based on <strong>smart rules</strong></li><li>Sends <strong>Slack alerts</strong> for untagged resources</li><li>Generates <strong>compliance reports</strong></li><li>Runs daily via <strong>EventBridge</strong></li></ol><p><strong>Total cost:</strong> £3/month<br><strong>Time saved:</strong> 10 hours/week<br><strong>Audit result:</strong> Passed with zero findings</p><h3>How It Works</h3><p>The core idea is <strong>pattern inference</strong>.</p><p>Instead of forcing developers to tag everything, the system <strong>learns from naming conventions and existing tags</strong>.</p><h3>Example 1: Team Inference from Resource Names</h3><p>If you have resources like:</p><pre>lambda-payments-processor<br>lambda-payments-validator<br>dynamodb-payments-transactions</pre><p>The tool infers they belong to the <strong>payments team</strong>.</p><p>It automatically applies:</p><pre>Team: payments<br>Project: payment-processing<br>Environment: production</pre><h3>Example 2: Cost Center Inheritance</h3><p>Imagine you already have several resources tagged:</p><pre>CostCenter: engineering-platform</pre><p>When a new resource appears in the <strong>same VPC</strong>, the tool automatically inherits the tag.</p><pre>CostCenter: engineering-platform</pre><h3>Example 3: Owner from CloudTrail</h3><p>If a Lambda was created by:</p><pre>agni.banerjee@company.com</pre><p>The system tags it with:</p><pre>Owner: agni.banerjee<br>CreatedBy: agni.banerjee@company.com<br>CreationDate: 2026-02-14</pre><p>CloudTrail becomes the source of truth.</p><h3>The Core Tagging Engine</h3><pre>import boto3<br>import re<br>from datetime import datetime<br>from typing import Dict, Optional<br><br>class SmartTagger:<br>    &quot;&quot;&quot;<br>    Intelligent AWS resource tagging engine.<br>    &quot;&quot;&quot;<br>    def __init__(self):<br>        self.session = boto3.Session()<br>    def infer_team_from_name(self, resource_name: str) -&gt; Optional[str]:<br>        patterns = [<br>            r&#39;^[a-z]+-([a-z]+)-&#39;,<br>            r&#39;-([a-z]+)-(prod|dev|staging)&#39;,<br>            r&#39;^([a-z]+)-&#39;,<br>        ]<br>        for pattern in patterns:<br>            match = re.search(pattern, resource_name.lower())<br>            if match:<br>                team = match.group(1)<br>                if team not in [&#39;prod&#39;,&#39;dev&#39;,&#39;staging&#39;,&#39;test&#39;,&#39;lambda&#39;,&#39;ec2&#39;,&#39;rds&#39;]:<br>                    return team<br>        return None<br>    def infer_environment(self, resource_name: str, account_id: str) -&gt; str:<br>        name_lower = resource_name.lower()<br>        if &#39;prod&#39; in name_lower:<br>            return &#39;production&#39;<br>        if &#39;dev&#39; in name_lower:<br>            return &#39;development&#39;<br>        if &#39;staging&#39; in name_lower:<br>            return &#39;staging&#39;<br>        if &#39;test&#39; in name_lower:<br>            return &#39;test&#39;<br>        account_envs = {<br>            &#39;111111111111&#39;: &#39;production&#39;,<br>            &#39;222222222222&#39;: &#39;development&#39;,<br>            &#39;333333333333&#39;: &#39;staging&#39;<br>        }<br>        return account_envs.get(account_id, &#39;unknown&#39;)<br>    def generate_tags(self, resource: Dict) -&gt; Dict[str, str]:<br>        tags = {}<br>        resource_name = resource.get(&#39;name&#39;, &#39;&#39;)<br>        account_id = resource.get(&#39;account_id&#39;, &#39;&#39;)<br>        team = self.infer_team_from_name(resource_name)<br>        if team:<br>            tags[&#39;Team&#39;] = team<br>            tags[&#39;Project&#39;] = f&quot;{team}-project&quot;<br>        tags[&#39;Environment&#39;] = self.infer_environment(resource_name, account_id)<br>        tags[&#39;ManagedBy&#39;] = &#39;auto-tagger&#39;<br>        tags[&#39;LastTagged&#39;] = datetime.now().strftime(&#39;%Y-%m-%d&#39;)<br>        return tags</pre><h3>The Resource Scanner</h3><p>This component scans every AWS service for resources.</p><pre>class ResourceScanner:<br><br>SUPPORTED_SERVICES = [<br>        &#39;ec2&#39;,&#39;lambda&#39;,&#39;rds&#39;,&#39;dynamodb&#39;,&#39;s3&#39;,<br>        &#39;ecs&#39;,&#39;eks&#39;,&#39;elasticache&#39;,&#39;sqs&#39;,<br>        &#39;sns&#39;,&#39;kinesis&#39;,&#39;cloudwatch&#39;<br>    ]<br>    def __init__(self):<br>        self.session = boto3.Session()<br>    def scan_all_resources(self):<br>        all_resources = []<br>        for service in self.SUPPORTED_SERVICES:<br>            print(f&quot;Scanning {service}...&quot;)<br>            resources = self.scan_service(service)<br>            all_resources.extend(resources)<br>        return all_resources</pre><h3>The Tagging Executor</h3><p>This safely applies tags and supports <strong>dry-run mode</strong>.</p><pre>class TaggingExecutor:<br>def __init__(self, dry_run=True):<br>        self.dry_run = dry_run<br>        self.session = boto3.Session()<br>    def apply_tags(self, resource, tags):<br>        existing = resource.get(&#39;existing_tags&#39;, {})<br>        new_tags = {k:v for k,v in tags.items() if k not in existing}<br>        if not new_tags:<br>            print(&quot;Already tagged&quot;)<br>            return False<br>        if self.dry_run:<br>            print(&quot;DRY RUN:&quot;, new_tags)<br>            return False<br>        client = self.session.client(&#39;resourcegroupstaggingapi&#39;)<br>        client.tag_resources(<br>            ResourceARNList=[resource[&#39;arn&#39;]],<br>            Tags=new_tags<br>        )<br>        return True</pre><h3>The Complete Workflow</h3><pre>def auto_tag_all_resources(dry_run=True):<br>scanner = ResourceScanner()<br>    tagger = SmartTagger()<br>    executor = TaggingExecutor(dry_run)<br>    resources = scanner.scan_all_resources()<br>    for resource in resources:<br>        generated_tags = tagger.generate_tags(resource)<br>        executor.apply_tags(resource, generated_tags)</pre><h3>Slack Alerts</h3><p>Nobody checks logs.</p><p>Everyone checks Slack.</p><pre>def send_slack_report(resources, tagged_count):<br>message = {<br>        &quot;text&quot;: &quot;Daily AWS Tagging Report&quot;,<br>        &quot;blocks&quot;:[<br>            {<br>                &quot;type&quot;:&quot;section&quot;,<br>                &quot;text&quot;:{<br>                    &quot;type&quot;:&quot;mrkdwn&quot;,<br>                    &quot;text&quot;:f&quot;Resources: {len(resources)}&quot;<br>                }<br>            }<br>        ]<br>    }</pre><h3>Deployment</h3><p>This runs as a <strong>Lambda triggered nightly by EventBridge</strong>.</p><pre>def lambda_handler(event, context):<br>auto_tag_all_resources(dry_run=False)<br>    return {<br>        &#39;statusCode&#39;:200,<br>        &#39;body&#39;:&#39;Tagging completed&#39;<br>    }</pre><p>EventBridge schedule:</p><pre>cron(0 2 * * ? *)</pre><p>Runs every night at <strong>2 AM</strong>.</p><h3>Real Results After 3 Months</h3><h3>Before</h3><ul><li>30% resources tagged</li><li>No tagging compliance</li><li>10 hours/week manual work</li><li>Failed first audit review</li></ul><h3>After</h3><ul><li>95% resources tagged</li><li>100% compliance for new resources</li><li>0 hours manual tagging</li><li>Passed audit with zero findings</li></ul><h3>Cost savings discovered</h3><ul><li>£8K/month in orphaned dev resources</li><li>£3K/month abandoned experiments</li><li>£2K/month duplicate staging environments</li></ul><p><strong>Total savings: £13K/month</strong></p><h3>The Tag That Changed Everything</h3><p>The <strong>Owner</strong> tag.</p><p>Before:</p><blockquote><em>“Who owns this Lambda?”</em></blockquote><p>After:</p><blockquote><em>Check the Owner tag.</em></blockquote><p>One lookup. Problem solved.</p><h3>Common Pitfalls</h3><h3>Tag value limits</h3><p>AWS limits tag values to <strong>256 characters</strong>.</p><h3>Some resources can’t be tagged</h3><p>Certain CloudWatch resources and policies have limitations.</p><h3>Cross-account tagging</h3><p>Requires <strong>role assumption across accounts</strong>.</p><h3>Tag propagation</h3><p>Some services don’t propagate tags to subresources.</p><p>Example: Lambda doesn’t tag its CloudWatch logs automatically.</p><h3>What I Learned</h3><p><strong>Start with inference, not enforcement</strong></p><p>If you infer tags automatically, developers don’t need to think about governance.</p><p><strong>CloudTrail is gold</strong></p><p>It tells you who created what.</p><p><strong>Run tagging daily</strong></p><p>Don’t wait for an audit.</p><p><strong>Slack beats logs</strong></p><p>People read Slack.</p><p><strong>Dry-run first</strong></p><p>Test for a week before enabling real tagging.</p><h3>The Audit Moment</h3><p>The auditor asked:</p><blockquote><em>“Show me all production databases owned by the data team.”</em></blockquote><p>Before this tool, that would take hours.</p><p>With tagging:</p><pre>aws resourcegroupstaggingapi get-resources \<br>--tag-filters Key=Environment,Values=production \<br>              Key=Team,Values=data \<br>--resource-type-filters dynamodb</pre><p>Five seconds.</p><p>Complete list.</p><p>Audit passed.</p><h3>Want the Code?</h3><p>Full auto-tagger on GitHub:</p><p><a href="https://github.com/agnee008/auto-tagger">https://github.com/agnee008/auto-tagger</a></p><p>Includes:</p><ul><li>Complete tagging engine</li><li>All service scanners</li><li>Slack integration</li><li>CDK deployment</li><li>CloudWatch dashboard</li><li>Tag policies</li><li>Docker image for local runs</li></ul><h3>Why You Probably Need This</h3><p>If you:</p><ul><li>Have more than <strong>50 AWS resources</strong></li><li>Work in a team larger than <strong>5 engineers</strong></li><li>Need <strong>compliance visibility</strong></li><li>Care about <strong>cost attribution</strong></li></ul><p>Manual tagging will not scale.</p><p>Automation will.</p><h3>Quick Setup</h3><ol><li>Clone the repo</li><li>Run dry-run mode</li><li>Check generated tags</li><li>Adjust inference rules</li><li>Run live</li><li>Schedule daily EventBridge trigger</li></ol><p>After that:</p><p>You never manually tag again.</p><p>And when compliance asks questions, you’ll have answers.</p><p><strong>— -</strong></p><p><em>*About the Author: Agnibes Banerjee is a Lead AWS Data Engineer with 8 years of experience building scalable data solutions. Previously at Dyson (UK), IBM (UK), and currently at Barclays (India), specializing in cloud-native architectures, real-time streaming, and regulatory compliance automation.*</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00cb6d77b172" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Debug Lambda Functions in Production (Without Breaking Things)]]></title>
            <link>https://medium.com/@agnee008/how-i-debug-lambda-functions-in-production-without-breaking-things-42f15ed8cab4?source=rss-9a8762b15d90------2</link>
            <guid isPermaLink="false">https://medium.com/p/42f15ed8cab4</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Agnibesh Banerjee]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 11:53:56 GMT</pubDate>
            <atom:updated>2026-02-22T11:59:55.733Z</atom:updated>
            <content:encoded><![CDATA[<p>You know that feeling when a Lambda function fails in production but works perfectly in your tests?</p><p>Yeah, me too. Every single week.</p><p>Last month I spent four hours debugging a Lambda that was randomly failing for about 2% of requests. The logs said <strong>timeout</strong>, but the function ran in 200ms locally.</p><p>The issue? It was trying to connect to a DynamoDB table in the wrong region, but only for specific partition keys that lived on slower shards.</p><p>I would never have found that without the debugging techniques I’m about to share.</p><p>These aren’t the usual “add more logging” tips you see in AWS docs. These are the messy, real-world techniques I use when production is on fire and I need answers fast.</p><h3>The Problem with Lambda Debugging</h3><p>Traditional debugging doesn’t really work with Lambda:</p><ul><li>You can’t attach a debugger</li><li>You can’t SSH into anything</li><li>You can’t fully reproduce production locally</li><li>You can’t set breakpoints</li><li>Code runs and disappears</li></ul><p>So what do we do?</p><p>We get creative.</p><h3>Technique 1: The Poor Man’s Profiler</h3><p>When a Lambda is slow but you don’t know why, instrument every function call.</p><p>Yes, this involves logging. But instead of logging what happens, log <strong>how long everything takes</strong>.</p><p>This shows exactly where time is being spent.</p><h3>Timing decorator template</h3><pre>import time<br>import functools<br>import json<br><br>def timeit(func):<br>    &quot;&quot;&quot;Decorator to time any function and log results.&quot;&quot;&quot;<br>    @functools.wraps(func)<br>    def wrapper(*args, **kwargs):<br>        start = time.time()<br>        result = func(*args, **kwargs)<br>        duration_ms = (time.time() - start) * 1000<br>        print(json.dumps({<br>            &#39;function&#39;: func.__name__,<br>            &#39;duration_ms&#39;: round(duration_ms, 2),<br>            &#39;timestamp&#39;: time.time()<br>        }))<br>        return result<br>    return wrapper</pre><h3>Use it everywhere</h3><pre>@timeit<br>def query_database(user_id):<br>    pass<br><br>@timeit<br>def call_external_api():<br>    pass<br>@timeit<br>def lambda_handler(event, context):<br>    user_id = event[&#39;user_id&#39;]<br>    data = query_database(user_id)<br>    result = call_external_api()<br>    return {&#39;statusCode&#39;: 200, &#39;body&#39;: json.dumps(result)}</pre><h3>CloudWatch output</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*o4c3paRo66EIkfWTAkMv8g.png" /></figure><pre>{&quot;function&quot;: &quot;query_database&quot;, &quot;duration_ms&quot;: 45.2}<br>{&quot;function&quot;: &quot;call_external_api&quot;, &quot;duration_ms&quot;: 1523.8}<br>{&quot;function&quot;: &quot;lambda_handler&quot;, &quot;duration_ms&quot;: 1589.3}</pre><p>Boom. The external API is the bottleneck.</p><p>This saved me three hours last week debugging a “slow Lambda” that was actually waiting on a third-party service.</p><h3>Technique 2: Structured Logging That Doesn’t Suck</h3><p>CloudWatch Logs Insights becomes powerful if your logs are structured.</p><p><strong>Don’t do this:</strong></p><pre>print(f&quot;User {user_id} processed successfully&quot;)</pre><p><strong>Do this:</strong></p><pre>import json<br>import time<br><br>def log(event_type, **data):<br>    print(json.dumps({<br>        &#39;event&#39;: event_type,<br>        &#39;timestamp&#39;: time.time(),<br>        **data<br>    }))</pre><h3>Usage</h3><pre>log(&#39;user_processed&#39;,<br>    user_id=user_id,<br>    items_count=len(items),<br>    duration_ms=123)</pre><h3>Query with Logs Insights</h3><pre>fields @timestamp, event, user_id, duration_ms<br>| filter event = &quot;user_processed&quot;<br>| stats avg(duration_ms) by user_id</pre><p>Now you can instantly:</p><ul><li>find slow users</li><li>track error rates</li><li>identify edge cases</li><li>investigate strange failures</li></ul><p>All because you logged JSON instead of random strings.</p><h3>Technique 3: Sampling for High-Volume Functions</h3><p>If your Lambda handles 10,000 requests per minute, logging everything will explode both logs and cost.</p><p>Instead, sample.</p><pre>import random<br>def should_log(sample_rate=0.01):<br>    return random.random() &lt; sample_rate<br><br>def lambda_handler(event, context):<br>    debug = should_log(0.01)  # 1%<br>if debug:<br>        log(&#39;request_start&#39;, event=event)<br>    result = process_data(event)<br>    if debug:<br>        log(&#39;request_end&#39;, result=result)<br>    return result</pre><p>For errors, always log:</p><pre>try:<br>    result = process_data(event)<br>except Exception as e:<br>    log(&#39;error&#39;, error=str(e), traceback=traceback.format_exc())<br>    raise</pre><p>You get a representative sample without drowning in logs.</p><h3>Technique 4: The Canary Request</h3><p>Want to know your Lambda is broken before users do?</p><p>Send it a fake request every five minutes and alert if it fails.</p><p>Use EventBridge to trigger a canary Lambda.</p><pre>import boto3, json<br>lambda_client = boto3.client(&#39;lambda&#39;)<br>def canary_handler(event, context):<br>    test_payload = {<br>        &#39;user_id&#39;: &#39;canary-user-12345&#39;,<br>        &#39;test&#39;: True<br>    }<br>    response = lambda_client.invoke(<br>        FunctionName=&#39;my-production-lambda&#39;,<br>        InvocationType=&#39;RequestResponse&#39;,<br>        Payload=json.dumps(test_payload)<br>    )<br>    result = json.loads(response[&#39;Payload&#39;].read())<br>    if response[&#39;StatusCode&#39;] != 200 or &#39;errorMessage&#39; in result:<br>        send_alert(&quot;Lambda failed&quot;)<br>        return {&#39;status&#39;: &#39;FAIL&#39;}<br>    return {&#39;status&#39;: &#39;OK&#39;}</pre><p>EventBridge runs this every five minutes.</p><p>If it fails, you get alerted before users notice.</p><p>Cost: a couple of dollars per month.<br> Peace of mind: enormous.</p><h3>Technique 5: Use X-Ray When Things Are Slow</h3><p>AWS X-Ray is overlooked and incredibly useful.</p><p>Enable it in Lambda settings, then:</p><pre>pip install aws-xray-sdk</pre><pre>from aws_xray_sdk.core import xray_recorder, patch_all<br>patch_all()<br>@xray_recorder.capture(&#39;process_order&#39;)<br>def process_order(order_id):<br>    pass<br></pre><p>Now you get a visual timeline showing:</p><ul><li>DynamoDB latency</li><li>S3 upload time</li><li>external API calls</li><li>bottlenecks in your code</li></ul><p>X-Ray once revealed a Lambda making <strong>15 sequential DynamoDB calls</strong> instead of using batch_get_item. One line change reduced runtime from 28 seconds to 3.</p><h3>Technique 6: Correlation IDs Across Lambdas</h3><p>Tracking requests across multiple Lambdas is painful.</p><p>Pass a correlation ID through everything.</p><pre>import uuid<br>correlation_id = event.get(&#39;correlation_id&#39;) or str(uuid.uuid4())<br>log(&#39;request_start&#39;, correlation_id=correlation_id)</pre><p>Now you can search logs for a single ID and trace the entire request flow.</p><h3>Technique 7: Dead Letter Queues Are Debugging Gold</h3><p>DLQs aren’t just for failures. They’re forensic evidence.</p><p>Pull failed events and analyze patterns:</p><pre>messages = sqs.receive_message(<br>    QueueUrl=&#39;DLQ_URL&#39;,<br>    MaxNumberOfMessages=10<br>)</pre><p>I once discovered all failures had user IDs starting with 0. They were being treated as numbers, and &quot;0&quot; became False.</p><p>Would never have caught it without DLQ analysis.</p><h3>Technique 8: Environment Variables for Emergency Debugging</h3><p>When something breaks in production and you need more visibility immediately:</p><pre>import os<br>DEBUG = os.environ.get(&#39;DEBUG&#39;, &#39;false&#39;).lower() == &#39;true&#39;</pre><p>Flip the variable in the console. No deploy needed.</p><p>Just remember to turn it off later.</p><h3>The “War Room” Debugging Checklist</h3><p>When production is on fire:</p><ol><li>Check CloudWatch metrics</li><li>Check X-Ray traces</li><li>Search logs for errors</li><li>Trace correlation IDs</li><li>Inspect DLQ messages</li><li>Enable DEBUG if needed</li><li>Run canary tests</li><li>Instrument slow code</li><li>Check region/AZ issues</li><li>Compare working vs failing events</li></ol><h3>Real Example: The Case of the Mysterious Timeouts</h3><p>Lambda timing out for 2% of requests.</p><p><strong>Step 1:</strong> CloudWatch metrics showed random timeouts.<br> <strong>Step 2:</strong> Added timing decorator.<br> <strong>Step 3:</strong> Logs showed DynamoDB call took 28 seconds.<br> <strong>Step 4:</strong> X-Ray showed connection latency.<br> <strong>Step 5:</strong> Lambda in eu-west-2. Table in us-east-1.</p><p>Most requests hit cache. The unlucky 2% crossed the Atlantic.</p><p>Fix took five minutes once the cause was clear.</p><h3>My Lambda Debugging Toolkit</h3><p>Every new Lambda gets:</p><ul><li>structured JSON logging</li><li>timing decorator</li><li>correlation ID support</li><li>full-context error logging</li><li>sampling logic</li><li>X-Ray ready</li><li>DLQ configured</li><li>canary health check</li><li>DEBUG env switch</li><li>CloudWatch dashboards</li></ul><p>Setup time: ~30 minutes<br> Time saved: hours every week</p><h3>What I Don’t Do Anymore</h3><p>After years of debugging Lambdas:</p><ul><li>I don’t try to perfectly reproduce locally</li><li>I don’t rely on random print statements</li><li>I don’t assume dev equals prod</li><li>I don’t ignore small error rates</li><li>I don’t skip X-Ray</li><li>I don’t delete DLQ messages</li></ul><h3>The Lesson That Changed Everything</h3><p>Log the thing you think is impossible.</p><p>“That timeout can’t be DynamoDB.”</p><p>“That region mismatch can’t happen.”</p><p>“That field is always populated.”</p><p>Every time I’ve said “that’s impossible,” that’s exactly where the bug was.</p><p>The bug hides in the obvious place you didn’t bother to check.</p><h3>Want the Code?</h3><p>All debugging helpers and templates:</p><p><strong>Github — </strong><a href="https://github.com/agnee008/lambda_debug_toolkit/blob/main/lambda_debug_toolkit.py"><strong>lambda-debugging-toolkit</strong></a></p><p>Includes:</p><ul><li>timing decorator</li><li>structured logger</li><li>correlation ID middleware</li><li>canary template</li><li>X-Ray setup</li><li>CloudWatch dashboard</li></ul><p>Use them. Modify them. Save yourself some pain.</p><p><strong>Where to find me:</strong></p><p>- <a href="https://medium.com/@agnee008"><strong>Medium</strong></a>: Technical deep-dives on data engineering</p><p>- <a href="https://www.linkedin.com/in/agnibeshbanerjee"><strong>LinkedIn</strong></a>: Connect and discuss architecture patterns</p><p>- <a href="https://github.com/agnee008"><strong>GitHub</strong></a>: Production-ready code and templates</p><p><em>About the Author: Agnibes Banerjee is a Lead AWS Data Engineer with 8 years of experience building scalable data solutions. Previously at Dyson (UK), IBM (UK), and currently at Barclays (India), specializing in cloud-native architectures, real-time streaming, and regulatory compliance automation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=42f15ed8cab4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Reduced AWS Data Pipeline Costs by 67% Without Sacrificing Performance]]></title>
            <link>https://medium.com/@agnee008/how-i-reduced-aws-data-pipeline-costs-by-67-without-sacrificing-performance-e023d15c4051?source=rss-9a8762b15d90------2</link>
            <guid isPermaLink="false">https://medium.com/p/e023d15c4051</guid>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Agnibesh Banerjee]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 17:42:38 GMT</pubDate>
            <atom:updated>2026-02-19T13:52:59.944Z</atom:updated>
            <content:encoded><![CDATA[<h3>The £500K Problem</h3><p>Six months into running our production data infrastructure, I got the email every engineer dreads:</p><blockquote><em>“We need to talk about the AWS bill.”</em></blockquote><p>Our monthly cloud costs had ballooned to <strong>£75,000</strong>, nearly <strong>£1 million annually</strong> just for data pipelines. Leadership wanted answers, and “cloud is expensive” wasn’t going to cut it.</p><p>After three months of systematic optimization, I reduced our monthly bill to <strong>£25,000</strong>, a <strong>67% reduction </strong>while actually improving performance and reliability.</p><p>Here’s exactly how I did it, with tactics you can implement immediately.</p><h3>The Cost Audit: Where Was the Money Going?</h3><p>Before optimizing anything, I needed visibility.</p><p>I used <strong>AWS Cost Explorer</strong> and enforced resource tagging to build a cost breakdown.</p><h3>Original Monthly Breakdown (£75,000)</h3><ul><li><strong>Amazon S3:</strong> £28,000 (37%)</li><li><strong>AWS Glue:</strong> £18,500 (25%)</li><li><strong>Amazon DynamoDB:</strong> £12,000 (16%)</li><li><strong>AWS Lambda:</strong> £8,500 (11%)</li><li><strong>Data Transfer:</strong> £5,000 (7%)</li><li><strong>Amazon Athena:</strong> £3,000 (4%)</li></ul><p><strong>The shock:</strong><br> 37% of our budget was S3 storage.</p><p>We were storing <strong>800 TB</strong> of data, most of it never accessed after 30 days.</p><h3>Strategy 1: Intelligent S3 Lifecycle Management</h3><h3>The Problem</h3><p>Everything lived in <strong>S3 Standard</strong> indefinitely.</p><p>Two-year-old data cost the same as yesterday’s data despite being accessed once per quarter.</p><h3>The Solution</h3><p>Implement lifecycle policies based on real access patterns.</p><pre>import boto3<br><br>s3 = boto3.client(&#39;s3&#39;)<br><br>lifecycle_policy = {<br>    &#39;Rules&#39;: [<br>        {<br>            &#39;Id&#39;: &#39;Move to IA after 30 days&#39;,<br>            &#39;Status&#39;: &#39;Enabled&#39;,<br>            &#39;Transitions&#39;: [<br>                {&#39;Days&#39;: 30, &#39;StorageClass&#39;: &#39;STANDARD_IA&#39;},<br>                {&#39;Days&#39;: 90, &#39;StorageClass&#39;: &#39;GLACIER_IR&#39;},<br>                {&#39;Days&#39;: 180, &#39;StorageClass&#39;: &#39;GLACIER&#39;},<br>                {&#39;Days&#39;: 365, &#39;StorageClass&#39;: &#39;DEEP_ARCHIVE&#39;}<br>            ]<br>        }<br>    ]<br>}<br><br>s3.put_bucket_lifecycle_configuration(<br>    Bucket=&#39;production-data-lake&#39;,<br>    LifecycleConfiguration=lifecycle_policy<br>)</pre><h3>Impact</h3><p><strong>Monthly savings:</strong> £16,800<br><strong>Annual savings:</strong> £201,600<br><strong>Reduction:</strong> 60%</p><h3>Additional Optimization: Intelligent-Tiering</h3><p>For unpredictable workloads:</p><pre>s3.put_bucket_intelligent_tiering_configuration(<br>    Bucket=&#39;analytics-data-lake&#39;,<br>    Id=&#39;auto-tiering-config&#39;,<br>    IntelligentTieringConfiguration={<br>        &#39;Id&#39;: &#39;auto-tiering-config&#39;,<br>        &#39;Status&#39;: &#39;Enabled&#39;,<br>        &#39;Tierings&#39;: [<br>            {&#39;Days&#39;: 90, &#39;AccessTier&#39;: &#39;ARCHIVE_ACCESS&#39;},<br>            {&#39;Days&#39;: 180, &#39;AccessTier&#39;: &#39;DEEP_ARCHIVE_ACCESS&#39;}<br>        ]<br>    }<br>)</pre><p><strong>Result:</strong> S3 costs dropped from <strong>£28,000 → £11,200/month</strong></p><h3>Strategy 2: Right-Size DynamoDB Tables</h3><h3>The Problem</h3><p>Tables were provisioned for peak load 24/7.</p><ul><li>Peak: 10,000 RCU/WCU</li><li>Average: 1,500</li><li>Night/weekends: 200</li></ul><p>We were paying for unused capacity most of the time.</p><h3>The Solution</h3><ul><li>Switch variable workloads to <strong>on-demand</strong></li><li>Keep provisioned for predictable traffic</li><li>Enable autoscaling where needed</li></ul><pre>dynamodb.update_table(<br>    TableName=&quot;orders-table&quot;,<br>    BillingMode=&quot;PAY_PER_REQUEST&quot;<br>)</pre><p><strong>Result:</strong> DynamoDB costs dropped from <strong>£12,000 → £4,500/month</strong></p><h3>Strategy 3: Optimize AWS Glue Jobs</h3><h3>The Problem</h3><p>Glue jobs were our second-largest expense.</p><p>Common issues:</p><ul><li>Default 10 DPUs regardless of data size</li><li>Jobs ran even with no new data</li><li>Standard workers used unnecessarily</li></ul><h3>The Solution</h3><p><strong>1. Dynamic DPU allocation</strong></p><pre>def calculate_optimal_dpus(input_size_gb):<br>    if input_size_gb &lt; 100:<br>        return 2<br>    elif input_size_gb &lt; 500:<br>        return 5<br>    elif input_size_gb &lt; 1000:<br>        return 10<br>    return 20</pre><p><strong>2. Skip runs when no new data</strong></p><p><strong>3. Enable job bookmarks</strong></p><pre>--job-bookmark-option job-bookmark-enable</pre><h3>Impact</h3><ul><li>Average DPUs: 10 → 5</li><li>Skip rate: 40%</li><li>Reduced runtime costs dramatically</li></ul><p><strong>Result:</strong> Glue costs dropped from <strong>£18,500 → £6,800/month</strong></p><h3>Strategy 4: Lambda Right-Sizing &amp; Concurrency Control</h3><h3>The Problem</h3><p>Default 128 MB memory caused:</p><ul><li>slower execution</li><li>higher total cost</li><li>timeouts &amp; retries</li></ul><h3>The Solution</h3><p>Use Lambda Power Tuning to find optimal memory.</p><p><strong>Key discovery:</strong><br> Higher memory often runs faster and costs less.</p><p>Also removed unnecessary reserved concurrency:</p><pre>lambda_client.delete_function_concurrency(<br>    FunctionName=&#39;batch-processor-function&#39;<br>)</pre><p><strong>Result:</strong> Lambda costs dropped from <strong>£8,500 → £3,200/month</strong></p><h3>Strategy 5: Eliminate Data Transfer Costs</h3><h3>The Problem</h3><p>£5,000/month in transfer costs from:</p><ul><li>cross-region replication</li><li>developer downloads</li><li>cross-AZ transfers</li></ul><h3>The Solution</h3><h3>1. VPC Endpoints (Free)</h3><pre>ec2.create_vpc_endpoint(<br>    VpcId=&#39;vpc-12345&#39;,<br>    ServiceName=&#39;com.amazonaws.eu-west-2.s3&#39;,<br>    VpcEndpointType=&#39;Gateway&#39;<br>)</pre><p><strong>Savings:</strong> ~£3,000/month</p><h3>2. CloudFront for frequent downloads</h3><p>Cache dev data instead of direct S3 pulls.</p><p><strong>Result:</strong> Transfer costs dropped from <strong>£5,000 → £800/month</strong></p><h3>Strategy 6: Athena Query Optimization</h3><h3>The Problem</h3><p>Athena charges per TB scanned. Analysts were scanning entire tables.</p><h3>The Solution</h3><ul><li>Partition data</li><li>Convert to Parquet</li><li>Enforce partition filters</li></ul><p><strong>Bad query:</strong> scans 5 TB → £19.50<br><strong>Optimized query:</strong> scans 150 GB → £0.59</p><p><strong>Result:</strong> Athena costs dropped from <strong>£3,000 → £600/month</strong></p><h3>Cost Reduction Summary</h3><p><strong>S3</strong><br> Before: £28,000 → After: £11,200<br> Savings: £16,800 (60%)</p><p><strong>Glue</strong><br> Before: £18,500 → After: £6,800<br> Savings: £11,700 (63%)</p><p><strong>DynamoDB</strong><br> Before: £12,000 → After: £4,500<br> Savings: £7,500 (62%)</p><p><strong>Lambda</strong><br> Before: £8,500 → After: £3,200<br> Savings: £5,300 (62%)</p><p><strong>Data Transfer</strong><br> Before: £5,000 → After: £800<br> Savings: £4,200 (84%)</p><p><strong>Athena</strong><br> Before: £3,000 → After: £600<br> Savings: £2,400 (80%)</p><h3>Total</h3><p><strong>£75,000 → £25,100</strong><br><strong>67% reduction</strong></p><p><strong>Annual savings: ~£600K</strong></p><h3>Automation: Monitor Costs Daily</h3><p>Don’t wait for month-end surprises.</p><p>Set daily alerts via Cost Explorer + SNS.</p><pre>if total_cost_gbp &gt; alert_threshold:<br>    sns.publish(<br>        TopicArn=&#39;arn:aws:sns:region:acct:cost-alerts&#39;,<br>        Subject=&#39;AWS Daily Cost Alert&#39;,<br>        Message=message<br>    )</pre><h3>Lessons Learned</h3><h3>What Worked</h3><ul><li>Start with cost visibility</li><li>Target high-impact wins first</li><li>Automate everything</li><li>Monitor daily</li></ul><h3>Mistakes I Made</h3><ul><li>Over-optimizing small services</li><li>Breaking a report with Glacier storage</li><li>Not communicating data retention changes</li><li>Delaying tagging strategy</li></ul><h3>Unexpected Wins</h3><ul><li>VPC endpoints are free</li><li>Glue bookmarks save huge compute</li><li>Intelligent-Tiering works great for unknown patterns</li><li>512 MB Lambda often cheaper than 128 MB</li></ul><h3>Reduce Your AWS Costs This Week</h3><h3>Day 1</h3><p>Audit costs and tag resources</p><h3>Day 2</h3><p>Apply S3 lifecycle rules &amp; delete unused resources</p><h3>Day 3–4</h3><p>Optimize DynamoDB, Lambda, and Glue</p><h3>Day 5</h3><p>Add alerts and automation</p><h3>Conclusion</h3><p>The savings didn’t come from switching services.</p><p>They came from <strong>using the right configuration for each workload</strong>:</p><ul><li>S3 lifecycle policies</li><li>DynamoDB billing mode alignment</li><li>Glue dynamic scaling</li><li>Right-sized Lambda memory</li><li>VPC endpoints for free networking</li><li>Athena partitions + Parquet</li></ul><p><strong>That £600K in savings funded three additional engineers.</strong></p><p>Start with visibility, capture quick wins, and automate.</p><p>Your finance team will notice.</p><h3>Tools &amp; Scripts</h3><p>GitHub:<br> 👉 <a href="https://github.com/agnee008/aws-cost-optimization/blob/main/s3_lifecycle_optimizer.py"><strong>github.com/agnee008/aws-cost-optimization</strong></a></p><p>Includes:</p><ul><li>lifecycle policy generator</li><li>Lambda tuning automation</li><li>Glue DPU calculator</li><li>cost monitoring scripts</li><li>Athena analyzer</li></ul><p><strong>Where to find me:</strong></p><p>- <a href="https://medium.com/@agnee008"><strong>Medium</strong></a>: Technical deep-dives on data engineering</p><p>- <a href="https://www.linkedin.com/in/agnibeshbanerjee"><strong>LinkedIn</strong></a>: Connect and discuss architecture patterns</p><p>- <a href="https://github.com/agnee008"><strong>GitHub</strong></a>: Production-ready code and templates</p><p><em>About the Author: Agnibes Banerjee is a Lead AWS Data Engineer with 8 years of experience building scalable data solutions. Previously at Dyson (UK), IBM (UK), and currently at Barclays (India), specializing in cloud-native architectures, real-time streaming, and regulatory compliance automation.</em></p><p>#DataEngineering #AWS #EventDrivenArchitecture #DataMesh #FinTech #CloudArchitecture #RealtimeData #UKTech</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e023d15c4051" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kinesis Data Streams vs EventBridge: A Real-World Decision Framework for Financial Services]]></title>
            <link>https://medium.com/@agnee008/kinesis-data-streams-vs-eventbridge-a-real-world-decision-framework-for-financial-services-173c8f58a8f4?source=rss-9a8762b15d90------2</link>
            <guid isPermaLink="false">https://medium.com/p/173c8f58a8f4</guid>
            <category><![CDATA[kinesis]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[aws-eventbridge]]></category>
            <dc:creator><![CDATA[Agnibesh Banerjee]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 06:03:50 GMT</pubDate>
            <atom:updated>2026-02-14T06:10:12.704Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The £2M Question I Had to Answer at a FinTech giant</strong></p><p>When architecting our regulatory reporting pipeline, I faced a critical decision: AWS Kinesis Data Streams or Amazon EventBridge? The choice would determine our latency profile, operational overhead, and annual AWS costs exceeding £2 million.</p><p>After implementing a lot of PoCs, I’ve learned when each service truly shines, and when choosing the wrong one creates expensive technical debt.</p><p><strong>The Problem: Not All Streaming is Created Equal</strong></p><p>Both services move data in real-time, but they solve fundamentally different problems:</p><p>- <strong>Kinesis Data Streams</strong>: High-throughput ordered streaming (think Apache Kafka)</p><p>- <strong>EventBridge</strong>: Event routing and orchestration (think intelligent message bus)</p><p>The confusion arises because <strong>both can technically solve the same use case</strong>, but one will do it elegantly while the other requires duct tape and workarounds.</p><p><strong>Real-World Context: What I Built</strong></p><p>Working in a FinTech giant, we process 50,000+ financial events per second:</p><p>- Trade executions from multiple exchanges</p><p>- Credit decisions from risk assessment engines</p><p>- Customer profile updates from CRM systems</p><p>- Regulatory reports to FCA and partner banks</p><p>At my earlier organisation, we handled:</p><p>- 100,000+ IoT sensor readings per second</p><p>- Product usage analytics from millions of devices</p><p>- Real-time performance monitoring</p><p>- Predictive maintenance triggers</p><p><strong><em>Different problems. Different solutions.</em></strong></p><p><strong>Architecture Comparison</strong></p><p><strong>Kinesis Data Streams Architecture</strong></p><pre>Data Sources → Kinesis Stream (Shards) → Consumers (Parallel Processing)<br>↓ ↓ ↓<br>Multiple Ordered within shard Process in order<br>Producers Partitioned by key Checkpoint progress</pre><p><strong>Key Characteristics:</strong></p><p>- Ordered within partition (shard)</p><p>- Multiple consumers can read same stream</p><p>- Data retained 1–365 days</p><p>- You manage shard capacity</p><p>- Throughput: MB/sec per shard</p><p><strong>EventBridge Architecture</strong></p><pre>Event Sources → Event Bus → Rules (Pattern Matching) → Multiple Targets<br>↓ ↓ ↓ ↓<br>Any source Schema Registry Content filtering 20+ AWS services<br>JSON events Auto-discovery No code required + Custom endpoints</pre><p><strong>Key Characteristics:</strong></p><p>- No ordering guarantee</p><p>- Event-driven routing</p><p>- Built-in transformations</p><p>- Schema management included</p><p>- Serverless (no capacity planning)</p><p><strong>The Decision Framework: 8 Critical Questions</strong></p><p><strong>1. Do You Need Strict Ordering?</strong></p><p><strong>Use Kinesis if:</strong></p><p>- Processing financial transactions in sequence</p><p>- Order of events changes business logic</p><p>- Example: Trade settlement requires chronological processing</p><p><strong>Use EventBridge if:</strong></p><p>- Events are independent</p><p>- Order doesn’t matter for correctness</p><p>- Example: Customer profile updates from different sources</p><p><strong>My Experience:</strong></p><p>At my earlier organisation, sensor readings needed ordering (temp → pressure → humidity correlation).</p><p>At present in FinTech, credit decisions were independent — no ordering needed.</p><p><strong>Decision: Earlier Organisation→ Kinesis, Present Organisation→ EventBridge</strong></p><p><strong>2. How Many Consumers Read the Same Data?</strong></p><p><strong>Use Kinesis if:</strong></p><p>- Multiple teams need identical event stream</p><p>- Fan-out pattern (1 stream → N consumers)</p><p>- Each consumer processes at own pace</p><p>- Example: Raw trades → [Risk Analysis, Compliance, Analytics, ML Training]</p><p><strong>Use EventBridge if:</strong></p><p>- Different consumers need different event subsets</p><p>- Routing logic based on event content</p><p>- Example: High-value trades → Fraud detection, Low-value → Standard processing</p><p><strong>Code Example — Kinesis Fan-out:</strong></p><pre># Multiple Lambda functions reading same Kinesis stream<br><br>import boto3<br>import json<br>import base64<br><br>kinesis = boto3.client(&quot;kinesis&quot;)<br><br><br># Consumer 1: Risk Analysis<br>def risk_consumer(event, context):<br>    for record in event[&quot;Records&quot;]:<br>        trade = json.loads(<br>            base64.b64decode(record[&quot;kinesis&quot;][&quot;data&quot;])<br>        )<br>        calculate_var(trade)  # Value at Risk<br><br><br># Consumer 2: Compliance<br>def compliance_consumer(event, context):<br>    for record in event[&quot;Records&quot;]:<br>        trade = json.loads(<br>            base64.b64decode(record[&quot;kinesis&quot;][&quot;data&quot;])<br>        )<br>        check_regulations(trade)<br><br><br># Consumer 3: Analytics<br>def analytics_consumer(event, context):<br>    for record in event[&quot;Records&quot;]:<br>        trade = json.loads(<br>            base64.b64decode(record[&quot;kinesis&quot;][&quot;data&quot;])<br>        )<br>        update_dashboards(trade)<br><br><br># All three consume identical stream with different lag</pre><p><strong>Code Example — EventBridge Routing:</strong></p><pre># Different targets based on event pattern<br># No code required — configured in EventBridge console<br><br># Rule 1: High-value trades → Fraud detection<br>{<br>  &quot;source&quot;: [&quot;trading.execution&quot;],<br>  &quot;detail&quot;: {<br>    &quot;amount&quot;: [<br>      { &quot;numeric&quot;: [&quot;&gt;&quot;, 1000000] }<br>    ]<br>  }<br>}<br># Target: Lambda → fraud_detection_function<br><br><br># Rule 2: Options trades → Risk team<br>{<br>  &quot;source&quot;: [&quot;trading.execution&quot;],<br>  &quot;detail&quot;: {<br>    &quot;instrument_type&quot;: [&quot;OPTION&quot;]<br>  }<br>}<br># Target: SQS → risk_queue<br><br><br># Rule 3: All trades → Data lake<br>{<br>  &quot;source&quot;: [&quot;trading.execution&quot;]<br>}<br># Target: Kinesis Firehose → S3</pre><p><strong>3. What’s Your Throughput Pattern?</strong></p><p><strong>Use Kinesis if:</strong></p><p>- Sustained high throughput (GB/sec)</p><p>- Predictable traffic patterns</p><p>- Willing to manage shard scaling</p><p>- Cost-conscious at scale (cheaper for constant high load)</p><p><strong>Use EventBridge if:</strong></p><p>- Bursty traffic</p><p>- Unpredictable patterns</p><p>- Want zero capacity planning</p><p>- Cost-conscious at low/medium load (pay per event)</p><p><strong>Real Numbers from Production:</strong></p><blockquote>| Metric | Kinesis | EventBridge |</blockquote><blockquote>| — — — — | — — — — | — — — — — —|</blockquote><blockquote>| Peak throughput | 500 MB/sec | 50,000 events/sec |</blockquote><blockquote>| Shards/Capacity | 100 shards (manual) | Auto-scales |</blockquote><blockquote>| Monthly cost | £8,000 (predictable) | £2,500 (variable) |</blockquote><blockquote>| Ops overhead | Medium (shard mgmt) | Low (serverless) |</blockquote><p><strong>Cost Breakdown:</strong></p><pre># Kinesis cost calculation<br><br>shards = 100<br>cost_per_shard = 0.015   # USD per hour<br>hours_per_month = 730<br>put_payload_units = 500_000_000   # per month<br><br>kinesis_monthly = (<br>    (shards * cost_per_shard * hours_per_month) +   # Shard hours<br>    (put_payload_units * 0.014 / 1_000_000)         # PUT payload units<br>)<br><br># ≈ $1,095 + $7 = $1,102<br><br><br># EventBridge cost calculation<br><br>events_per_month = 1_500_000_000   # 1.5B events<br><br>eventbridge_monthly = (<br>    (events_per_month / 1_000_000) * 1.00   # First 1M free, then $1/million<br>)<br><br># ≈ $1,499<br><br><br># Kinesis cheaper at very high sustained throughput<br># EventBridge cheaper at moderate/bursty loads</pre><p><strong>4. Do You Need Replay Capability?</strong></p><p><strong>Use Kinesis if:</strong></p><p>- Must replay events for debugging</p><p>- Reprocess data with new logic</p><p>- Disaster recovery scenarios</p><p>- Retention: 1–365 days</p><p><strong>Use EventBridge if:</strong></p><p>- Archive for compliance only</p><p>- Replay is occasional (not core workflow)</p><p>- Retention: Up to indefinite with Archive</p><p><strong>My Use Case:</strong></p><p><strong>Kinesis Replay:</strong></p><pre># Bug found in ML model — reprocess last 7 days<br><br>import boto3<br>from datetime import datetime, timedelta<br><br>kinesis = boto3.client(&quot;kinesis&quot;)<br><br># Get shard iterator for 7 days ago<br>response = kinesis.get_shard_iterator(<br>    StreamName=&quot;sensor-data-stream&quot;,<br>    ShardId=&quot;shardId-000000000001&quot;,<br>    ShardIteratorType=&quot;AT_TIMESTAMP&quot;,<br>    Timestamp=datetime.utcnow() - timedelta(days=7)<br>)<br><br>shard_iterator = response[&quot;ShardIterator&quot;]<br><br># Reprocess all records<br>while shard_iterator:<br>    records = kinesis.get_records(<br>        ShardIterator=shard_iterator,<br>        Limit=1000<br>    )<br><br>    for record in records[&quot;Records&quot;]:<br>        reprocess_with_new_model(record[&quot;Data&quot;])<br><br>    shard_iterator = records.get(&quot;NextShardIterator&quot;)</pre><p><strong>EventBridge Archive:</strong></p><pre># Compliance audit — retrieve specific events<br><br>import boto3<br>from datetime import datetime<br><br>events = boto3.client(&quot;events&quot;)<br><br># Replay specific event pattern from archive<br>response = events.start_replay(<br>    ReplayName=&quot;compliance-audit-2024-q1&quot;,<br>    EventSourceArn=&quot;arn:aws:events:eu-west-2:123456789012:archive/trade-archive&quot;,<br>    EventStartTime=datetime(2024, 1, 1),<br>    EventEndTime=datetime(2024, 3, 31),<br>    Destination={<br>        &quot;Arn&quot;: &quot;arn:aws:events:eu-west-2:123456789012:event-bus/audit-bus&quot;<br>    }<br>)<br><br># Replay goes to separate audit bus — doesn&#39;t affect production</pre><p><strong>5. What About Schema Evolution?</strong></p><p><strong>Use EventBridge if:</strong></p><p>- Need automatic schema discovery</p><p>- Want schema registry built-in</p><p>- IDE autocomplete for events</p><p>- Breaking change detection</p><p><strong>Use Kinesis if:</strong></p><p>- Happy managing schemas separately (Glue Schema Registry)</p><p>- Already have schema tooling</p><p><strong>EventBridge Schema Registry in Action:</strong></p><pre>// EventBridge auto-discovers this schema<br>{<br>  &quot;detail-type&quot;: &quot;TradeExecuted&quot;,<br>  &quot;detail&quot;: {<br>    &quot;trade_id&quot;: &quot;TRD0000001234&quot;,<br>    &quot;instrument&quot;: &quot;AAPL&quot;,<br>    &quot;quantity&quot;: 100,<br>    &quot;price&quot;: 150.25<br>  }<br>}</pre><p><strong>Generated Python code:</strong></p><pre># Auto-generated from EventBridge schema<br><br>from aws_schema_registry import TradeExecuted<br><br>trade = TradeExecuted(<br>    trade_id=&quot;TRD0000001234&quot;,<br>    instrument=&quot;AAPL&quot;,<br>    quantity=100,<br>    price=150.25<br>)<br><br># IDE autocomplete works!<br># Type checking works!<br># Breaking changes detected at build time!</pre><p><strong>Kinesis + Glue Schema Registry:</strong></p><pre># Must manually configure schema registry<br><br>from aws_glue_schema_registry import SchemaRegistryClient<br><br>registry = SchemaRegistryClient(<br>    region=&quot;eu-west-2&quot;,<br>    registry_name=&quot;trading-schemas&quot;<br>)<br><br># Serialize with schema<br>serialized = registry.serialize(<br>    schema_name=&quot;TradeExecuted&quot;,<br>    data=trade_data<br>)<br><br>kinesis.put_record(<br>    StreamName=&quot;trades&quot;,<br>    Data=serialized,<br>    PartitionKey=trade_id<br>)</pre><p><strong>6. Integration Complexity?</strong></p><p><strong>Use EventBridge if:</strong></p><p>- Need to trigger 20+ AWS service types</p><p>- Want built-in integrations (no code)</p><p>- Cross-account/cross-region routing</p><p>- API destinations (SaaS webhooks)</p><p><strong>Use Kinesis if:</strong></p><p>- Custom processing logic required</p><p>- Need full control over consumption</p><p>- Integration with Apache Flink, Spark</p><p><strong>EventBridge Native Integrations (No Code Required):</strong></p><p>- ✅ Lambda, Step Functions, ECS, Batch</p><p>- ✅ SNS, SQS, Kinesis (yes, you can route to Kinesis!)</p><p>- ✅ CloudWatch Logs, EventBridge Archive</p><p>- ✅ API Gateway, AppSync</p><p>- ✅ CodePipeline, CodeBuild</p><p>- ✅ SageMaker Pipelines</p><p>- ✅ <strong>90+ SaaS integrations </strong>(Salesforce, Zendesk, Datadog, etc.)</p><p>- ✅ <strong>HTTP endpoints</strong> (any webhook)</p><p><strong>Example — Multi-target Routing:</strong></p><pre># EventBridge rule with 5 targets (NO CODE!)<br><br>{<br>  &quot;Targets&quot;: [<br>    {<br>      &quot;Arn&quot;: &quot;arn:aws:lambda:…:fraud-detection&quot;,<br>      &quot;Id&quot;: &quot;fraud-check&quot;<br>    },<br>    {<br>      &quot;Arn&quot;: &quot;arn:aws:sqs:…:risk-queue&quot;,<br>      &quot;Id&quot;: &quot;risk-analysis&quot;<br>    },<br>    {<br>      &quot;Arn&quot;: &quot;arn:aws:firehose:…:s3-delivery&quot;,<br>      &quot;Id&quot;: &quot;data-lake&quot;<br>    },<br>    {<br>      &quot;Arn&quot;: &quot;arn:aws:events:…:partner-bus&quot;,<br>      &quot;Id&quot;: &quot;cross-account&quot;,<br>      &quot;RoleArn&quot;: &quot;arn:aws:iam:…:cross-account-role&quot;<br>    },<br>    {<br>      &quot;Arn&quot;: &quot;https://api.slack.com/webhooks/...&quot;,<br>      &quot;Id&quot;: &quot;slack-notification&quot;,<br>      &quot;HttpParameters&quot;: {<br>        &quot;HeaderParameters&quot;: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;<br>        }<br>      }<br>    }<br>  ]<br>}</pre><p><strong>Same with Kinesis requires custom code for each target.</strong></p><p><strong>7. Operational Overhead?</strong></p><p><strong>Kinesis Operational Tasks:</strong></p><p>- ⚠️ Monitor shard utilization</p><p>- ⚠️ Scale shards up/down (can use auto-scaling)</p><p>- ⚠️ Handle shard splits/merges</p><p>- ⚠️ Manage consumer checkpointing</p><p>- ⚠️ Deal with ProvisionedThroughputExceededException</p><p>- ⚠️ Configure CloudWatch alarms</p><p><strong>EventBridge Operational Tasks:</strong></p><p>- ✅ Create rules</p><p>- ✅ Monitor failed invocations</p><p>- ✅ That’s it</p><p><strong>A Real Incident :</strong></p><pre>03:42 AM — PagerDuty Alert<br><br>Error:<br>WriteProvisionedThroughputExceededException:<br>Rate exceeded for shard shardId-000000000042<br><br>Root Cause:<br>Marketing campaign drove 3× normal device activations<br><br>Fix Required:<br>1. Emergency shard split (≈10 minutes downtime)<br>2. Update consumer code for new shard count<br>3. Redeploy consumers<br>4. Verify checkpointing<br><br>Time to Resolution: 45 minutes</pre><p><strong>Same scenario with EventBridge: Auto-scaled. No alert. No action needed.</strong></p><p><strong>8. Latency Requirements?</strong></p><p>Both provide sub-second latency, but characteristics differ:</p><p><strong>Kinesis:</strong></p><p>- Latency: ~200ms (producer → consumer)</p><p>- Consistent, predictable</p><p>- Batching can reduce to ~70ms</p><p><strong>EventBridge:</strong></p><p>- Latency: ~500ms (p50), ~1s (p99)</p><p>- Variable based on routing complexity</p><p>- Not suitable for &lt;100ms requirements</p><p><strong>My Recommendation:</strong></p><p>- <strong>&lt;100ms required?</strong>→ Kinesis</p><p>- <strong>&lt;1s acceptable?</strong> → EventBridge</p><p>- <strong>&lt;5s acceptable?</strong> → EventBridge (definitely)</p><p><strong>The Decision Matrix</strong></p><blockquote>| Your Requirement | Choose Kinesis | Choose EventBridge |</blockquote><blockquote>| — — — — — — — — — | — — — — — — — — | — — — — — — — — — -|</blockquote><blockquote>| Strict ordering within partition | ✅ Yes | ❌ No |</blockquote><blockquote>| Multiple consumers, same data | ✅ Yes | ⚠️ Possible but awkward |</blockquote><blockquote>| Sustained high throughput (GB/sec) | ✅ Yes | ❌ Too expensive |</blockquote><blockquote>| Bursty/unpredictable traffic | ⚠️ Overprovisioning needed | ✅ Yes |</blockquote><blockquote>| Frequent replay/reprocessing | ✅ Yes | ⚠️ Archive only |</blockquote><blockquote>| Schema management built-in | ⚠️ Separate service | ✅ Yes |</blockquote><blockquote>| 20+ target integrations | ❌ Custom code | ✅ Built-in |</blockquote><blockquote>| Cross-account routing | ⚠️ Complex | ✅ Easy |</blockquote><blockquote>| Zero operational overhead | ❌ Manage shards | ✅ Serverless |</blockquote><blockquote>| Sub-100ms latency | ✅ Yes | ❌ No |</blockquote><blockquote>| Event pattern routing | ❌ Consumer filters | ✅ Built-in |</blockquote><p><strong>Real-World Decision Examples</strong></p><p><strong>When I Chose Kinesis ( IoT Platform)</strong></p><p><strong>Requirement:</strong></p><p>- 100,000 sensor readings/sec from vacuum cleaners</p><p>- Ordered processing (temperature before pressure)</p><p>- Multiple ML models consuming same stream</p><p>- Real-time dashboards</p><p>- 7-day replay for model training</p><p><strong>Why Kinesis:</strong></p><p>- ✅ Ordering critical for correlation analysis</p><p>- ✅ Fan-out to 5+ consumers</p><p>- ✅ High sustained throughput</p><p>- ✅ 7-day retention for ML training</p><p>- ✅ Predictable costs</p><p><strong>When I Chose EventBridge (Trading data)</strong></p><p><strong>Requirement:</strong></p><p>- 50,000 events/sec (trades, credit, customer)</p><p>- Different event types to different targets</p><p>- No ordering required</p><p>- Bursty (market hours vs. overnight)</p><p>- Cross-account sharing with partner banks</p><p><strong>Why EventBridge:</strong></p><p>- ✅ Pattern-based routing (no custom code)</p><p>- ✅ Schema registry for IDE support</p><p>- ✅ Bursty traffic (no capacity planning)</p><p>- ✅ Cross-account built-in</p><p>- ✅ Archive for compliance</p><p>- ✅ Lower operational overhead</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-DsgdTDdUxVf1hzybQnCQ.png" /></figure><p><strong>Performance Tuning Tips</strong></p><p><strong>Kinesis Optimization</strong></p><p><strong>1. Right-size shards:</strong></p><pre># Calculate required shards<br><br>import math<br><br>writes_per_second = 50000<br>avg_record_size_kb = 1<br><br>writes_mb_per_sec = (writes_per_second * avg_record_size_kb) / 1024<br><br># Each shard: 1 MB/sec write, 2 MB/sec read<br>required_shards = math.ceil(writes_mb_per_sec / 1)<br><br>print(f&quot;Required shards: {required_shards}&quot;)</pre><p><strong>2. Use batching:</strong></p><pre># Batch writes (up to 500 records)<br><br>import json<br><br>records = []<br><br>for i in range(500):<br>    records.append({<br>        &quot;Data&quot;: json.dumps(event_data),<br>        &quot;PartitionKey&quot;: partition_key<br>    })<br><br>kinesis.put_records(<br>    StreamName=&quot;my-stream&quot;,<br>    Records=records<br>)<br><br># 500x fewer API calls = lower latency + cost</pre><p><strong>3. Optimize partition keys:</strong></p><pre># BAD: Hot shard (all to same partition)<br>partition_key = &quot;CONSTANT&quot;<br><br><br># GOOD: Even distribution<br>import uuid<br>partition_key = str(uuid.uuid4())<br><br><br># BETTER: Logical grouping + distribution<br>partition_key = f&quot;{instrument_code}-{uuid.uuid4().hex[:8]}&quot;</pre><p><strong>EventBridge Optimization</strong></p><p><strong>1. Precise event patterns:</strong></p><pre>// BAD: Catches everything, filters in Lambda (expensive)<br>{<br>  &quot;source&quot;: [&quot;trading&quot;]<br>}</pre><pre>// GOOD: Filter in EventBridge (free)<br>{<br>  &quot;source&quot;: [&quot;trading&quot;],<br>  &quot;detail-type&quot;: [&quot;TradeExecuted&quot;],<br>  &quot;detail&quot;: {<br>    &quot;amount&quot;: [<br>      { &quot;numeric&quot;: [&quot;&gt;&quot;, 1000000] }<br>    ],<br>    &quot;status&quot;: [&quot;SETTLED&quot;]<br>  }<br>}</pre><p><strong>2. Use InputTransformer:</strong></p><pre>// Transform event before target (no Lambda needed)<br>{<br>  &quot;InputPathsMap&quot;: {<br>    &quot;trade_id&quot;: &quot;$.detail.trade_id&quot;,<br>    &quot;amount&quot;: &quot;$.detail.amount&quot;<br>  },<br>  &quot;InputTemplate&quot;: &quot;\&quot;Trade &lt;trade_id&gt; executed for $&lt;amount&gt;\&quot;&quot;<br>}</pre><p><strong>3. Batch to reduce Lambda invocations:</strong></p><pre>// EventBridge Pipes can batch events<br>{<br>  &quot;BatchSize&quot;: 100,<br>  &quot;MaximumBatchingWindowInSeconds&quot;: 10<br>}</pre><p><strong>Monitoring &amp; Observability</strong></p><p><em>Kinesis Metrics (CloudWatch)</em></p><pre># Key metrics to monitor<br>metrics = [<br>    &quot;IncomingRecords&quot;,                    # Records/sec<br>    &quot;IncomingBytes&quot;,                      # MB/sec<br>    &quot;WriteProvisionedThroughputExceeded&quot;, # Throttling<br>    &quot;GetRecords.IteratorAgeMilliseconds&quot;, # Consumer lag<br>    &quot;PutRecord.Success&quot;,                  # Success rate<br>]<br><br># Alert on throttling<br>cloudwatch.put_metric_alarm(<br>    AlarmName=&quot;kinesis-throttling&quot;,<br>    MetricName=&quot;WriteProvisionedThroughputExceeded&quot;,<br>    Threshold=10,<br>    EvaluationPeriods=2,<br>    ComparisonOperator=&quot;GreaterThanThreshold&quot;<br>)</pre><p><em>EventBridge Metrics</em></p><pre># Key metrics to monitor<br>metrics = [<br>    &quot;Invocations&quot;,        # Events matched<br>    &quot;FailedInvocations&quot;,  # Failed deliveries<br>    &quot;ThrottledRules&quot;,     # Rate limiting<br>    &quot;TriggeredRules&quot;,     # Rules executed<br>]<br><br># Alert on failures<br>cloudwatch.put_metric_alarm(<br>    AlarmName=&quot;eventbridge-failures&quot;,<br>    MetricName=&quot;FailedInvocations&quot;,<br>    Threshold=100,<br>    EvaluationPeriods=1<br>)</pre><p><strong>Cost Optimization Strategies</strong></p><p><strong><em>Kinesis Cost Reduction</em></strong></p><p>1<strong>. </strong>Use On-Demand (if unpredictable):</p><pre># On-demand mode (no shard management)<br><br>kinesis.create_stream(<br>    StreamName=&quot;my-stream&quot;,<br>    StreamModeDetails={<br>        &quot;StreamMode&quot;: &quot;ON_DEMAND&quot;<br>    }<br>)<br><br># Pay per GB ingested + GB retrieved</pre><p>2. Right-size retention:</p><pre># Don&#39;t pay for retention you don&#39;t use<br><br>kinesis.decrease_stream_retention_period(<br>    StreamName=&quot;my-stream&quot;,<br>    RetentionPeriodHours=24  # Default is 24, max 8760<br>)</pre><p><strong><em>EventBridge Cost Reduction</em></strong></p><p>1. Filter aggressively:</p><pre>// Each matched event costs money<br>// Filter as early as possible<br>{<br>  &quot;detail&quot;: {<br>    &quot;amount&quot;: [<br>      { &quot;numeric&quot;: [&quot;&gt;&quot;, 100] }<br>    ],  // Filter here<br>    &quot;status&quot;: [&quot;ACTIVE&quot;]  // Not in Lambda<br>  }<br>}</pre><p>2. Use archive selectively:</p><pre>// Archive only what you need<br>{<br>  &quot;EventPattern&quot;: {<br>    &quot;detail-type&quot;: [&quot;HighValueTrade&quot;]  // Not every event<br>  }<br>}</pre><p><strong>My Recommendations</strong></p><p><em>Choose Kinesis when:</em></p><p>✅ Ordering is critical</p><p>✅ Fan-out to multiple consumers</p><p>✅ Sustained high throughput (&gt;100 MB/sec)</p><p>✅ Frequent replay required</p><p>✅ Already using Kafka-like patterns</p><p><em>Choose EventBridge when:</em></p><p>✅ Event routing based on content</p><p>✅ Integrating with AWS services</p><p>✅ Bursty/unpredictable traffic</p><p>✅ Want zero operational overhead</p><p>✅ Need schema management</p><p>✅ Cross-account/cross-region</p><p><em>Use both when:</em></p><p>✅ High-throughput ingestion + intelligent routing</p><p>✅ Ordered processing + fan-out to varied targets</p><p>✅ Migration/transition period</p><p><strong>Conclusion: It’s Not “Either/Or”</strong></p><p>After implementing both at scale, here’s my mental model:</p><p><strong><em>Kinesis = High-performance ordered queue</em></strong></p><p>Use when you need Kafka-like guarantees on AWS</p><p><strong><em>EventBridge = Intelligent event router</em></strong></p><p>Use when you need serverless orchestration</p><p>The best architectures often combine both:</p><p>- Kinesis for the “firehose” of ordered data</p><p>- EventBridge for routing processed insights</p><p><a href="https://github.com/agnee008/EventbridgeVsKinesis">GitHub Code- streaming_comparison.py</a></p><p><strong><em>The decision isn’t about which is “better”, it’s about which solves your specific problem most elegantly.</em></strong></p><p><strong>Have questions about Kinesis or EventBridge? </strong>Drop them in the comments. I read and respond to every one.</p><p><em>*About the Author: Agnibes Banerjee is a Lead AWS Data Engineer with 8 years of experience building scalable data solutions. Previously at Dyson (UK), IBM (UK), and currently at Barclays (India), specializing in real-time streaming architectures and event-driven systems.*</em></p><p><strong>Connect:</strong></p><p>- <a href="https://linkedin.com/in/agnibeshbanerjee">LinkedIn</a></p><p>- <a href="https://github.com/agnee008">GitHub</a></p><p>- <a href="https://medium.com/@agnee008">Medium</a></p><p>#DataEngineering #AWS #Kinesis #EventBridge #RealTimeData #StreamProcessing #CloudArchitecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=173c8f58a8f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Real-Time Financial Data Pipeline with AWS EventBridge and Data Mesh Principles]]></title>
            <link>https://medium.com/@agnee008/building-a-real-time-financial-data-pipeline-with-aws-eventbridge-and-data-mesh-principles-695c7e29a9df?source=rss-9a8762b15d90------2</link>
            <guid isPermaLink="false">https://medium.com/p/695c7e29a9df</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[finops]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Agnibesh Banerjee]]></dc:creator>
            <pubDate>Fri, 13 Feb 2026 06:47:31 GMT</pubDate>
            <atom:updated>2026-02-13T11:34:17.839Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why This Matters in Modern Data Engineering</strong></p><p>After spending 3+ years working on enterprise-scale data solutions in the UK at some top product based companies, I’ve seen firsthand how the industry is shifting from batch-oriented ETL to real-time, event-driven architectures. The financial services sector, particularly in the UK, is increasingly adopting event-driven patterns to meet regulatory requirements and deliver real-time insights.</p><p>I’m sharing this architecture because it solves real problems I’ve encountered in production environments, and I believe the data engineering community can benefit from these battle-tested patterns.</p><p><strong>The Problem: Siloed Financial Data</strong></p><p>Traditional data warehouses struggle with three critical challenges:</p><p>- <strong>Latency</strong>: Batch processes create hours-long delays in data availability</p><p>- <strong>Ownership</strong>: Centralized teams become bottlenecks for domain-specific insights</p><p>- <strong>Compliance</strong>: Regulatory requirements demand real-time audit trails</p><p>Having implemented regulatory reporting systems at my present organisation, I witnessed how these challenges compound in financial services where milliseconds matter and compliance is non-negotiable.</p><p><strong>The Solution: Event-Driven Data Mesh Architecture</strong></p><p>I’m building an open-source reference architecture that combines:</p><ul><li><strong>AWS EventBridge</strong> for event-driven orchestration</li><li><strong>Data Mesh principles</strong> for decentralized ownership</li><li><strong>Serverless patterns</strong> for cost-efficient scaling</li></ul><figure><img alt="AWS Financial Data Mesh: Architecture Deep Dive" src="https://cdn-images-1.medium.com/max/1024/1*aMMRJJ6untoRnDleTxPsZw.png" /></figure><p><strong>Technical Deep Dive</strong></p><p><strong>1. Event Ingestion with EventBridge</strong></p><p>Unlike traditional message queues, EventBridge provides:</p><ul><li><strong>Schema discovery</strong>: Automatic detection of event structures</li><li><strong>Archive &amp; replay</strong>: Built-in event store for debugging</li><li><strong>Cross-account routing</strong>: Essential for Data Mesh federation</li></ul><pre>import boto3<br>import json<br>from datetime import datetime<br><br>eventbridge = boto3.client(&#39;events&#39;)<br><br>def publish_trade_event(trade_data):<br>    &quot;&quot;&quot;<br>    Publish trade execution event to custom event bus<br>    &quot;&quot;&quot;<br>    event = {<br>        &#39;Source&#39;: &#39;investment.trading&#39;,<br>        &#39;DetailType&#39;: &#39;TradeExecuted&#39;,<br>        &#39;Detail&#39;: json.dumps({<br>            &#39;trade_id&#39;: trade_data[&#39;id&#39;],<br>            &#39;instrument&#39;: trade_data[&#39;instrument&#39;],<br>            &#39;quantity&#39;: trade_data[&#39;quantity&#39;],<br>            &#39;price&#39;: trade_data[&#39;price&#39;],<br>            &#39;timestamp&#39;: datetime.utcnow().isoformat(),<br>            &#39;trader_id&#39;: trade_data[&#39;trader_id&#39;]<br>        }),<br>        &#39;EventBusName&#39;: &#39;financial-data-mesh-bus&#39;<br>    }<br>    <br>    response = eventbridge.put_events(Entries=[event])<br>    <br>    if response[&#39;FailedEntryCount&#39;] &gt; 0:<br>        raise Exception(f&quot;Failed to publish event: {response[&#39;Entries&#39;]}&quot;)<br>    <br>    return response[&#39;Entries&#39;][0][&#39;EventId&#39;]</pre><p><strong>2. Transformation with EventBridge Pipes</strong></p><p>EventBridge Pipes bridge the gap between EventBridge and other AWS services with built-in filtering and transformation:</p><pre># Lambda enrichment function invoked by EventBridge Pipe<br>def enrich_trade_event(event, context):<br>    &quot;&quot;&quot;<br>    Enrich trade events with reference data from DynamoDB<br>    &quot;&quot;&quot;<br>    import boto3<br>    <br>    dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>    instruments_table = dynamodb.Table(&#39;instruments-reference&#39;)<br>    <br>    for record in event[&#39;Records&#39;]:<br>        detail = json.loads(record[&#39;body&#39;])<br>        instrument_code = detail[&#39;instrument&#39;]<br>        <br>        # Fetch instrument metadata<br>        instrument = instruments_table.get_item(<br>            Key={&#39;instrument_code&#39;: instrument_code}<br>        )<br>        <br>        # Enrich the event<br>        detail[&#39;instrument_metadata&#39;] = {<br>            &#39;sector&#39;: instrument[&#39;Item&#39;][&#39;sector&#39;],<br>            &#39;currency&#39;: instrument[&#39;Item&#39;][&#39;currency&#39;],<br>            &#39;exchange&#39;: instrument[&#39;Item&#39;][&#39;exchange&#39;]<br>        }<br>        <br>        record[&#39;body&#39;] = json.dumps(detail)<br>    <br>    return event</pre><p><strong>3. Data Mesh Principles Implementation</strong></p><p><strong>Domain Ownership</strong>: Each business domain (Investment, Credit, Customer) owns its event schemas and data quality:</p><pre># Investment domain schema validation<br>from aws_lambda_powertools import Validator<br><br>trade_schema = {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;required&quot;: [&quot;trade_id&quot;, &quot;instrument&quot;, &quot;quantity&quot;, &quot;price&quot;],<br>    &quot;properties&quot;: {<br>        &quot;trade_id&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;pattern&quot;: &quot;^TRD[0-9]{10}$&quot;},<br>        &quot;instrument&quot;: {&quot;type&quot;: &quot;string&quot;},<br>        &quot;quantity&quot;: {&quot;type&quot;: &quot;number&quot;, &quot;minimum&quot;: 1},<br>        &quot;price&quot;: {&quot;type&quot;: &quot;number&quot;, &quot;minimum&quot;: 0},<br>        &quot;timestamp&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;format&quot;: &quot;date-time&quot;}<br>    }<br>}<br><br>@validator(inbound_schema=trade_schema)<br>def validate_trade(event, context):<br>    # Schema validation happens automatically<br>    return process_trade(event)</pre><p><strong>Self-Service Data Infrastructure</strong>: Infrastructure as Code with AWS CDK:</p><pre>from aws_cdk import (<br>    Stack,<br>    aws_events as events,<br>    aws_events_targets as targets,<br>    aws_lambda as lambda_,<br>    aws_sqs as sqs,<br>    aws_pipes as pipes<br>)<br><br>class DataMeshStack(Stack):<br>    def __init__(self, scope, construct_id, **kwargs):<br>        super().__init__(scope, construct_id, **kwargs)<br>        <br>        # Custom Event Bus for the Data Mesh<br>        event_bus = events.EventBus(<br>            self, &quot;FinancialDataMeshBus&quot;,<br>            event_bus_name=&quot;financial-data-mesh-bus&quot;<br>        )<br>        <br>        # Dead Letter Queue for failed events<br>        dlq = sqs.Queue(<br>            self, &quot;EventDLQ&quot;,<br>            retention_period=Duration.days(14)<br>        )<br>        <br>        # SQS Queue for buffering<br>        trade_queue = sqs.Queue(<br>            self, &quot;TradeQueue&quot;,<br>            dead_letter_queue=sqs.DeadLetterQueue(<br>                max_receive_count=3,<br>                queue=dlq<br>            )<br>        )<br>        <br>        # EventBridge Rule to route trade events<br>        rule = events.Rule(<br>            self, &quot;TradeEventRule&quot;,<br>            event_bus=event_bus,<br>            event_pattern=events.EventPattern(<br>                source=[&quot;investment.trading&quot;],<br>                detail_type=[&quot;TradeExecuted&quot;]<br>            )<br>        )<br>        <br>        rule.add_target(targets.SqsQueue(trade_queue))</pre><p><strong>Real-World Performance Metrics</strong></p><p>From my implementation at present organisation:</p><p>- <strong>Latency reduction</strong>: 4 hours → 30 seconds for regulatory reporting</p><p>- <strong>Cost optimization</strong>: 60% reduction vs. traditional EC2-based pipelines</p><p>- <strong>Scalability</strong>: Handles 50,000+ events/second during market peak</p><p><strong>Why This Architecture Matters for UK FinTech</strong></p><p>The UK’s financial services sector is rapidly adopting event-driven architectures for:</p><p>- <strong>Real-time risk management</strong>: Required by FCA regulations</p><p>- <strong>Open Banking</strong>: PSD2 compliance demands instant data sharing</p><p>- <strong>RegTech innovation</strong>: Automated compliance reporting</p><p>This pattern directly addresses challenges I’ve seen at UK institutions and aligns with the FCA’s technology strategy outlined in their 2024 digital transformation roadmap.</p><p><strong>What’s Next: Sharing More Real-World Patterns</strong></p><p>This is the first in a series of technical deep-dives where I’ll be sharing production-grade data engineering solutions. Based on the challenges I’ve tackled at Barclays, Dyson, and IBM, I plan to explore:</p><p><strong>Real-time streaming architectures:</strong></p><p>- Kinesis Data Streams vs. EventBridge: When to use each</p><p>- Building CDC pipelines with DynamoDB Streams</p><p>- Apache Kafka on AWS MSK for high-throughput scenarios</p><p><strong>Advanced transformation patterns:</strong></p><p>- PySpark optimization techniques from production workloads</p><p>- Delta Lake for ACID transactions in data lakes</p><p>- Data quality testing with dbt</p><p><strong>MLOps and real-time analytics:</strong></p><p>- Fraud detection with SageMaker in financial services</p><p>- Real-time feature engineering for ML models</p><p>- Model monitoring and drift detection</p><p><strong>Production-grade solutions:</strong></p><p>- Multi-region disaster recovery strategies</p><p>- Cost optimization lessons learned</p><p>- Security and compliance automation</p><p>Each article will include complete working code, infrastructure templates, and real-world performance metrics.</p><p><strong>Open Source Contribution</strong></p><p>I’m making all code, architecture diagrams, and infrastructure templates available on GitHub at <strong>github.com/agnibes/aws-financial-data-mesh</strong> to help other data engineers implementing similar solutions.</p><p>The repository includes:</p><p>- Complete working code samples with proper error handling</p><p>- CloudFormation/CDK templates ready for deployment</p><p>- Step-by-step deployment guides</p><p>- Cost analysis and optimization tips</p><p>- Production lessons learned</p><p>I believe in learning through real code, not just theory, so everything shared will be production-quality and deployable.</p><p><strong>Let’s Connect</strong></p><p>I’m sharing these solutions because:</p><p>1. The data engineering community helped me grow and its time to give back</p><p>2. UK FinTech faces unique challenges that deserve documented solutions</p><p>3. Real production code is more valuable than theoretical concepts</p><p><strong>Where to find me:</strong></p><p>- <a href="https://medium.com/@agnee008"><strong>Medium</strong></a>: Technical deep-dives on data engineering</p><p>- <a href="https://www.linkedin.com/in/agnibeshbanerjee"><strong>LinkedIn</strong></a>: Connect and discuss architecture patterns</p><p>- <a href="https://github.com/agnee008"><strong>GitHub</strong></a>: Production-ready code and templates</p><p><strong>Interested in event-driven architectures or real-time data pipelines?</strong> Let’s connect and share experiences. What are the biggest challenges in your data infrastructure?</p><p><strong>— -</strong></p><p><em>*About the Author: Agnibes Banerjee is a Lead AWS Data Engineer with 8 years of experience building scalable data solutions. Previously at Dyson (UK), IBM (UK), and currently at Barclays (India), specializing in cloud-native architectures, real-time streaming, and regulatory compliance automation.*</em></p><p>#DataEngineering #AWS #EventDrivenArchitecture #DataMesh #FinTech #CloudArchitecture #RealtimeData #UKTech</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=695c7e29a9df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>