<![CDATA[Stack Stories]]><![CDATA[Stack Stories]]>https://srinumadhav.hashnode.devRSS for NodeTue, 24 Nov 2026 10:52:17 GMT<![CDATA[en]]>60<![CDATA[Database Connection Management and Caching in Node.js: Best Practices for Production Applications]]><![CDATA[Database connection management is one of the most critical aspects of building robust, scalable applications. Poor connection handling can lead to…]]>https://srinumadhav.hashnode.dev/database-connection-management-and-caching-in-nodejs-best-practices-for-production-applicationshttps://srinumadhav.hashnode.dev/database-connection-management-and-caching-in-nodejs-best-practices-for-production-applications<![CDATA[KNEX]]><![CDATA[performance]]><![CDATA[Node.js]]><![CDATA[Databases]]><![CDATA[srinu madhav vysyaraju]]>Fri, 06 Feb 2026 13:54:37 GMT<![CDATA[

Introduction

Database connection management is one of the most critical aspects of building robust, scalable applications. Poor connection handling can lead to connection leaks, performance degradation, and application failures. In this post, we'll explore advanced patterns for managing database connections in Node.js applications, with a focus on connection caching, health checks, and graceful cleanup.

The Problem: Connection Overhead

Creating new database connections is expensive. Each connection involves:

  • Network handshakes
  • Authentication
  • Resource allocation
  • SSL/TLS negotiation

In serverless environments like AWS Lambda, this overhead becomes even more pronounced due to cold starts and execution time limits.

Solution: Smart Connection Caching

1. Connection Caching Pattern

let cachedMySQLConnection: mysql2.Connection | null = null;
let cachedKnexConnection: Knex | null = null;
let cachedOldConnection: mysql2.Connection | null = null;

const connectDatabase = async (credentials) => {
  if (cachedMySQLConnection) {
    try {
      // Health check before reusing
      await cachedMySQLConnection.execute('SELECT 1');
      logger.debug("Reusing healthy cached MySQL connection");
      return cachedMySQLConnection;
    } catch (healthCheckError) {
      logger.warn("Cached connection failed health check, creating new connection");
      await cleanupConnection(cachedMySQLConnection);
      cachedMySQLConnection = null;
    }
  }

  // Create new connection
  cachedMySQLConnection = await createNewConnection(credentials);
  return cachedMySQLConnection;
};

2. Health Check Strategy

The key insight is that cached connections might become stale due to:

  • Network timeouts
  • Database server restarts
  • Idle connection cleanup by proxies/load balancers

Solution: Lightweight Health Checks

// Quick health check - minimal overhead
await connection.execute('SELECT 1');

This approach:

  • ✅ Validates connection is alive
  • ✅ Minimal performance impact
  • ✅ Works across all database types
  • ✅ Faster than creating new connections

3. Graceful Connection Cleanup

export const closeAllConnections = async () => {
  try {
    if (cachedKnexConnection) {
      await cachedKnexConnection.destroy();
      cachedKnexConnection = null;
      logger.debug("Knex connection pool closed");
    }

    if (cachedMySQLConnection) {
      await cachedMySQLConnection.end();
      cachedMySQLConnection = null;
      logger.debug("MySQL connection closed");
    }

    if (cachedOldConnection) {
      await cachedOldConnection.end();
      cachedOldConnection = null;
      logger.debug("Legacy connection closed");
    }
  } catch (error: any) {
    logger.error("Error closing database connections", {
      error: error.message,
      errorName: error.name,
      errorStack: error.stack,
    });
  }
};

4. Error Handling and Recovery

export const queryDatabase = async (query, params) => {
  try {
    const connection = await connectDatabase(credentials);
    const [results] = await callWithRetry(() => connection.execute(query, params), 3);
    return { success: results };
  } catch (error) {
    logger.error(`Database error: ${error}`);

    // Reset connection on error to force fresh connection next time
    if (cachedMySQLConnection) {
      try {
        await cachedMySQLConnection.end();
      } catch (cleanupError) {
        logger.warn("Error cleaning up failed connection", JSON.stringify(cleanupError));
      }
      cachedMySQLConnection = null;
    }
    throw error;
  }
};

Advanced Patterns

1. Multiple Connection Types

For applications using multiple databases or connection methods:

interface ConnectionCache {
  mysql: mysql2.Connection | null;
  postgres: Knex | null;
  legacy: mysql2.Connection | null;
}

const connections: ConnectionCache = {
  mysql: null,
  postgres: null,
  legacy: null
};

Why Multiple Connections?

  1. Different Database Libraries

    • Raw mysql2: Fast, lightweight queries
    • Knex.js: Query builder/ORM for complex operations
    • Legacy connections: Separate database instances or older systems
  2. Different Use Cases

    • Simple queries: Direct mysql2 connection
    • Complex queries with joins: Knex connection
    • Legacy system integration: Separate connection pool
  3. Performance Optimization

    • Use the right tool for each specific query type
    • Maintain separate connection pools for different workloads

2. Connection Pool Management

For high-throughput applications, consider connection pooling:

const createKnexConnection = async (config) => {
  return knex({
    client: 'pg',
    connection: config,
    pool: {
      min: 1,
      max: 10,
      acquireTimeoutMillis: 30000,
      createTimeoutMillis: 30000,
      destroyTimeoutMillis: 5000,
      idleTimeoutMillis: 30000
    }
  });
};

3. Retry Logic with Exponential Backoff

const callWithRetry = async (fn, maxRetries = 3, baseDelay = 1000, maxDelay = 30000) => {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await fn();
    } catch (error) {
      if (attempt === maxRetries) throw error;

      const delay = Math.min(baseDelay * Math.pow(2, attempt - 1), maxDelay);
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
};

4. Parameterized Queries for Security

Always use parameterized queries to prevent SQL injection:

// ❌ Vulnerable to SQL injection
const query = `SELECT EnglishName FROM Carrier WHERE Code = "${flightCode}"`;

// ✅ Safe parameterized query
const query = `SELECT EnglishName FROM Carrier WHERE Code = ?`;
const [results] = await connection.execute(query, [flightCode]);

Benefits of This Approach

Performance Improvements

  • Reduced Latency: Reusing connections eliminates connection setup time
  • Lower CPU Usage: Fewer connection negotiations
  • Better Throughput: More time spent on actual work vs. connection management

Reliability Enhancements

  • Automatic Recovery: Failed connections are detected and replaced
  • Graceful Degradation: Applications continue working despite temporary connection issues
  • Resource Management: Proper cleanup prevents connection leaks

Serverless Optimization

  • Cold Start Mitigation: Cached connections survive across invocations
  • Cost Efficiency: Reduced execution time means lower costs
  • Better User Experience: Faster response times

Best Practices Summary

  1. Always implement health checks before reusing cached connections
  2. Handle connection failures gracefully with proper cleanup and retry logic
  3. Use connection pooling for high-concurrency applications
  4. Implement proper logging for debugging connection issues
  5. Clean up connections on application shutdown
  6. Monitor connection metrics to optimize pool sizes and timeouts
  7. Use parameterized queries to prevent SQL injection attacks
  8. Implement retry logic with exponential backoff for transient failures

Real-World Implementation Example

export const queryDataStore = async (secret, code) => {
  try {
    if (!secret) {
      logger.debug("Secret is null/undefined");
      return { failure: [] };
    }
    if (!code) {
      logger.debug("code is null/undefined");
      return { failure: [] };
    }

    const connection = await connectDatabase(secret);
    const query = `SELECT EnglishName FROM Carrier WHERE Code = ?`;
    const [results] = await callWithRetry(() => connection.execute(query, [code]), 3);
    return { success: results };
  }
  catch (error) {
    logger.error(`Database Service Error: ${error}`);
    // Reset cached connection on error
    if (cachedMySQLConnection) {
      try {
        await cachedMySQLConnection.end();
      } catch (cleanupError) {
        logger.warn("Error cleaning up failed connection", JSON.stringify(cleanupError));
      }
      cachedMySQLConnection = null;
    }
    throw error;
  }
};

Conclusion

Effective database connection management is crucial for production applications. By implementing connection caching with health checks, graceful error handling, and proper cleanup procedures, you can significantly improve your application's performance, reliability, and resource utilization.

The patterns shown here are particularly valuable in serverless environments but apply to any Node.js application that needs efficient database connectivity. Remember to monitor your connection usage and adjust pool sizes based on your specific workload patterns.

Key takeaways:

  • Cache connections but always validate their health
  • Handle multiple connection types appropriately
  • Implement proper error recovery and cleanup
  • Use parameterized queries for security
  • Monitor and optimize based on actual usage patterns

This approach has been battle-tested in production environments and can significantly improve your application's database performance and reliability.

]]><![CDATA[Debugging RDS Proxy Session Pinning: A Real-World Investigation]]><![CDATA[Learn why AWS RDS Proxy session pinning happens with Npgsql and how one connection string parameter fixes connection multiplexing issues. Includes…]]>https://srinumadhav.hashnode.dev/debugging-rds-proxy-session-pinning-a-real-world-investigationhttps://srinumadhav.hashnode.dev/debugging-rds-proxy-session-pinning-a-real-world-investigation<![CDATA[NPSQL]]><![CDATA[sessionPinning]]><![CDATA[PostgreSQL]]><![CDATA[rds]]><![CDATA[proxy]]><![CDATA[srinu madhav vysyaraju]]>Fri, 09 Jan 2026 14:09:35 GMT<![CDATA[

Picture this: You've just deployed AWS RDS Proxy to handle your growing traffic. The promise is elegant—100 application connections gracefully multiplexed down to just 10 database connections. Your infrastructure costs drop. Your database breathes easier. Everything should be perfect.

But then something strange happens.


The Silent Killer

Your monitoring dashboard shows an unusual pattern. The DatabaseConnectionsCurrentlySessionPinned metric is climbing. Slowly at first, then faster. Your connection pool—the very thing you added RDS Proxy to protect—starts exhausting during traffic spikes.

Hidden in your CloudWatch logs, a cryptic message repeats:

[WARN] The client session was pinned to the database connection 
for the remainder of the session. The proxy can't reuse this 
connection until the session ends.
Reason: SQL changed session settings that the proxy doesn't track.
Digest: "discard all"

Your beautiful 100-to-10 connection multiplexing has silently become 100-to-100. The proxy is there, it's working, but it's been neutered. Why?


The Invisible Culprit

Here's where it gets interesting: You search your entire codebase for "DISCARD". Nothing. You're not sending that command. Your code is clean. So who is?

The answer lies in a place developers rarely look—the default behavior of your database driver.

The Well-Intentioned Design

When you use Npgsql (the PostgreSQL driver for .NET), it does something clever. Every time a connection returns to the pool, Npgsql automatically sends DISCARD ALL to PostgreSQL. This resets the session state, ensuring the next user of that pooled connection gets a clean slate.

// Your code
using (var conn = dataSource.OpenConnection()) {
    // Do work
} // Connection returns to pool

// What Npgsql does behind the scenes:
// → DISCARD ALL

For direct database connections, this is brilliant. It prevents one request from accidentally affecting another through leftover session state.

But RDS Proxy sees this differently.


The Proxy's Dilemma

RDS Proxy is designed to be smart about connection multiplexing. It tracks certain session changes and can maintain them across multiplexed connections. But there are operations it can't track—operations that fundamentally change the session in ways the proxy can't safely share.

When RDS Proxy sees DISCARD ALL, it makes a decision: This connection is no longer safe to multiplex. The connection gets "pinned" to a single client for the rest of its lifetime.

What Triggers the Pin?

For PostgreSQL connections, RDS Proxy pins on:

TriggerWhy It Matters
DISCARD ALLResets all session state—too broad to track
SET commandsChanges session variables unpredictably
SQL > 16 KBExtended protocol parsing overhead
PREPARE statementsSession-specific query plans
Temporary tablesExist only in the session context
Advisory locksSession-level synchronization primitives
CursorsStateful result set navigation

The invisible DISCARD ALL from Npgsql falls squarely into the first category.


The One-Line Fix

The solution is almost anticlimactic in its simplicity:

// Add this one parameter
"No Reset On Close=true"

Your full connection string becomes:

var connectionString = 
    $"Host={proxyEndpoint};" +
    $"Database={database};" +
    $"Username={user};" +
    $"Password={password};" +
    $"Pooling=true;" +
    $"No Reset On Close=true;";  // ← This is the magic

This tells Npgsql: "Don't send DISCARD ALL when connections return to the pool."

Suddenly, your RDS Proxy starts doing what it was meant to do. Connections multiplex. Your DatabaseConnectionsCurrentlySessionPinned metric drops to near zero. The system breathes.


But Wait—Is This Safe?

This is the question that makes engineers nervous. You're disabling a safety mechanism. What could go wrong?

What You're Giving Up

Without DISCARD ALL, connections returned to the pool retain:

  • Session variables set via SET commands
  • Temporary tables and sequences
  • Prepared statements
  • Transaction isolation level changes

When It's Perfectly Safe

If your application:

  • ✅ Doesn't create temporary tables
  • ✅ Doesn't use SET to change session state
  • ✅ Doesn't rely on prepared statements persisting
  • ✅ Uses explicit transactions properly

Then No Reset On Close=true with RDS Proxy is not just safe—it's optimal.

The RDS Proxy Safety Net

Remember: RDS Proxy itself manages connection state between the proxy and database. When your application connection closes, the database connection goes back into the proxy's pool, where the proxy manages its lifecycle. You're not abandoning connection hygiene—you're delegating it to the proxy layer.


The Detective's Toolkit

How do you know if pinning is affecting you?

CloudWatch Metric

The most direct signal:

Namespace: AWS/RDS
Metric: DatabaseConnectionsCurrentlySessionPinned
Dimension: ProxyName=your-proxy-name

If this number is consistently high relative to your total connections, you have a pinning problem.

CloudWatch Logs Insights

Find what's causing the pins:

fields @timestamp, @message
| filter @message like /The client session was pinned/
| parse @message /Digest: "(?<command>.*?)"/
| stats count() by command
| sort count desc

This query groups pinning events by the SQL command that triggered them. If discard all dominates the results, you know the cause.

The Smoking Gun Query

See pinning rate over time:

fields @timestamp
| filter @message like /pinned/
| stats count() as pins by bin(5m)

If you see consistent pinning after every request, it's likely a driver default behavior issue.


Other Pinning Villains

The 16 KB Statement

PostgreSQL's extended query protocol becomes a pinning trigger when SQL exceeds 16 KB in text size. This often happens with:

// Dangerous: Inserting 1000 rows in one statement
INSERT INTO bookings (user_id, date) VALUES 
    (1, '2025-01-01'), 
    (2, '2025-01-02'),
    // ... 998 more rows
    (1000, '2025-01-10');  // This statement is > 16 KB!

Solution: Batch into smaller operations or use COPY protocol.

The Innocent SET Command

SET timezone = 'America/New_York';
SET search_path = tenant_schema;

These session-level configurations cause pinning.

Solution: Configure them as RDS Proxy initialization queries instead:

  1. RDS Console → Proxies → Your Proxy → Target Groups
  2. Edit target group
  3. Set "Session pinning filters" or initialization query

The Prepared Statement Trap

Some ORMs aggressively prepare statements:

// Behind the scenes
// PREPARE stmt1 AS SELECT * FROM users WHERE id = $1;
// EXECUTE stmt1(123);

Solution: Configure your ORM to use simple query protocol with RDS Proxy, or accept the pinning trade-off for read-heavy workloads where prepared statements offer significant performance gains.


The Production Playbook

Before You Deploy RDS Proxy

  1. Audit your driver defaults: Check if your database driver sends reset commands
  2. Review session state usage: Inventory any SET commands, temp tables, or cursors
  3. Measure SQL statement sizes: Log your largest queries to find 16 KB+ statements
  4. Enable enhanced logging: Turn on RDS Proxy logging to CloudWatch

After Deployment

  1. Set up alarms: Alert when DatabaseConnectionsCurrentlySessionPinned > 50% of total connections
  2. Monitor for patterns: Use Logs Insights to track which operations cause pinning
  3. Load test: Pinning issues often only appear under concurrent load
  4. Compare metrics: Watch DatabaseConnections vs DatabaseConnectionsCurrentlySessionPinned ratio

The Golden Metric

Pinning Efficiency = 1 - (Pinned Connections / Total Connections)

If this drops below 0.7 (70% efficiency), you're losing much of RDS Proxy's benefit.


The Architectural Perspective

RDS Proxy represents a shift in how we think about database connections. Traditionally:

Application Pool → Direct DB Connection
(Connection state managed by application)

With RDS Proxy:

Application → RDS Proxy Pool → Database Connection
(Connection state managed by proxy and database)

This introduces a new layer with its own state management rules. Understanding these rules—and configuring your drivers accordingly—is essential to unlocking the proxy's value.

When RDS Proxy Shines

  • High connection churn: Lots of short-lived connections
  • Bursty traffic: Sudden spikes in concurrent requests
  • Serverless architectures: Lambda functions opening many connections
  • Failover resilience: Graceful handling of database failures

When Pinning Negates the Benefits

If every connection pins, RDS Proxy becomes an expensive passthrough. The connection multiplexing benefit disappears, and you're left paying for a proxy that's essentially just forwarding connections 1:1.


The Story's Moral

The most insidious bugs aren't in your code—they're in the invisible behaviors of the tools you depend on.

A single flag, No Reset On Close=true, sits at the intersection of:

  • Database driver design philosophy
  • AWS proxy implementation details
  • Your application's connection pooling strategy

Miss it, and you deploy infrastructure that looks right on paper but fails under load. Find it, and you unlock the true potential of connection multiplexing.


Resources for the Curious

AWS Documentation

Npgsql Documentation

PostgreSQL


The Question to Ask

Next time you deploy database infrastructure, ask: What invisible behaviors are my tools bringing to the table?

Because sometimes, the difference between a struggling system and a smoothly scaling one is knowing which defaults to question.

]]>
<![CDATA[Lambda + Kafka: The Push-Pull Paradox Explained]]><![CDATA[Why your Lambda concurrency is capped by Kafka partitions — and everyt]]>https://srinumadhav.hashnode.dev/lambda-kafka-the-push-pull-paradox-explainedhttps://srinumadhav.hashnode.dev/lambda-kafka-the-push-pull-paradox-explained<![CDATA[kafka]]><![CDATA[AWS]]><![CDATA[serverless]]><![CDATA[srinu madhav vysyaraju]]>Tue, 16 Dec 2025 17:28:35 GMT<![CDATA[

The Paradox

Here's something that should bother you:

  • Kafka is built on a pull model. Consumers poll for messages. The broker is dumb, the consumer is smart.
  • Lambda is built on a push model. Events arrive, Lambda runs. No polling, no long-running processes.

So what happens when you connect Lambda to Kafka via MSK EventSource Mapping?

The answer reveals a hidden layer of infrastructure that has significant implications for scaling, cost, and failure handling — none of which are obvious from the AWS console.


The Hidden Consumer

When you create an EventSource Mapping between MSK and Lambda, AWS doesn't magically convert Kafka to push-based. Instead, AWS runs a managed Kafka consumer on your behalf.

┌─────────────────────────────────────────────────────────────────────┐
│                        AWS Managed Infrastructure                   │
│                                                                     │
│   ┌─────────────────────────────────────────────────────────────┐  │
│   │              Event Source Mapping Service                    │  │
│   │                                                              │  │
│   │   ┌────────────────────┐      ┌────────────────────────┐    │  │
│   │   │   Kafka Consumer   │      │    Lambda Invoker      │    │  │
│   │   │                    │      │                        │    │  │
│   │   │   • Polls MSK      │─────▶│   • Batches records    │    │  │
│   │   │   • Manages group  │      │   • Invokes Lambda     │    │  │
│   │   │   • Commits offsets│      │   • Handles retries    │    │  │
│   │   └────────────────────┘      └────────────────────────┘    │  │
│   │              ▲                            │                  │  │
│   └──────────────┼────────────────────────────┼──────────────────┘  │
│                  │                            │                     │
└──────────────────┼────────────────────────────┼─────────────────────┘
                   │ PULL                       │ PUSH
                   │                            ▼
            ┌──────┴──────┐              ┌─────────────┐
            │     MSK     │              │   Lambda    │
            │   Cluster   │              │  Function   │
            └─────────────┘              └─────────────┘

From Kafka's perspective, nothing changes. A consumer is polling, joining a consumer group, committing offsets. It happens to be managed by AWS rather than your code.

From Lambda's perspective, nothing changes. Events arrive, function runs. It doesn't know or care that Kafka is involved.

The EventSource Mapping is a translation layer — pull on one side, push on the other.


The Partition-Concurrency Trap

This architecture has a consequence that surprises many teams:

Your maximum Lambda concurrency equals your partition count.

Not your Lambda concurrency limit. Not your account limits. Your Kafka partition count.

Here's why:

Kafka's consumer model assigns each partition to exactly one consumer in a group. The ESM service respects this — it runs one "poller" per partition, and each poller invokes Lambda independently.

Topic: orders (4 partitions)

┌─────────────────────────────────────────────────────────┐
│            ESM Consumer Group                           │
│                                                         │
│  Poller 0 ──▶ Lambda    Poller 2 ──▶ Lambda            │
│  (P0)                   (P2)                            │
│                                                         │
│  Poller 1 ──▶ Lambda    Poller 3 ──▶ Lambda            │
│  (P1)                   (P3)                            │
│                                                         │
└─────────────────────────────────────────────────────────┘

Maximum concurrent Lambdas: 4 (regardless of Lambda limits)

With 4 partitions, you get at most 4 concurrent Lambda executions.

If you need to scale to 100 concurrent Lambdas, you need 100 partitions. This is a Kafka constraint leaking through the serverless abstraction.

The Scaling Equation

Max Concurrent Lambdas = Number of Partitions

Want more parallelism? Add partitions (requires topic recreation or careful expansion).

This is why partition count is one of the most important decisions when designing Kafka-based architectures — and why it's often under-provisioned by teams new to Kafka.


The "Always Running" Myth

A common concern: "If I have 15 partitions, does that mean 15 Lambdas running 24/7?"

No. This is the key economic advantage of the Lambda model.

The ESM polling service runs continuously — but that's AWS infrastructure you don't pay for directly. Lambda only runs when invoked with actual messages.

Traffic Pattern: Bursty

Timeline:
──────────────────────────────────────────────────────────────────▶
       │              │                              │
   [burst]        [burst]         (quiet)        [burst]
       │              │                              │
       ▼              ▼                              ▼
    Lambdas        Lambdas       No Lambdas       Lambdas
    running        running        ($0 cost)       running

No messages = no Lambda invocations = no Lambda cost.

Compare this to self-managed consumers:

AspectSelf-Managed (ECS/EKS)Lambda + ESM
Idle cost15 containers running 24/7Zero
Burst handlingRequires auto-scaling configAutomatic
Minimum monthly cost~$50-200$0 possible

For variable or bursty workloads, Lambda can be 10x cheaper. The crossover point where self-managed wins is sustained high-throughput processing — typically millions of messages per hour continuously.


Offset Management: You're Not in Control

With a native Kafka consumer, you decide when to commit offsets:

  • Commit before processing (at-most-once)
  • Commit after processing (at-least-once)
  • Commit atomically with output (exactly-once)

With Lambda + ESM, you have no control over offset commits. The ESM service commits automatically after successful Lambda invocation.

1. ESM polls batch of messages (offsets 100-199)
2. ESM invokes Lambda synchronously
3. Lambda processes records
4. Lambda returns success
5. ESM commits offset 200

This gives you at-least-once semantics by default. If Lambda times out or crashes after processing but before returning, the batch will be redelivered.

You cannot:

  • Commit offsets manually from Lambda code
  • Commit per-record (it's always per-batch)
  • Implement exactly-once semantics

If you need exactly-once, you need idempotent processing in your Lambda, or you need to move to self-managed consumers with transactions.


The Failure Handling Model

The ESM provides failure handling that you'd otherwise have to build yourself:

Retry Behavior

ConfigWhat It Does
RetryAttemptsNumber of retries before giving up on a batch
MaximumRecordAgeInSecondsSkip records older than this (escape hatch for poison pills)
BisectBatchOnFunctionErrorSplit batch in half on failure to isolate bad records
DestinationConfigSend failed records to SQS/SNS dead-letter queue

The Poison Pill Problem

Without special handling, one bad record can block an entire partition:

Batch: [good, good, BAD, good, good]

Standard retry: Entire batch fails repeatedly
                Partition processing blocked
                Consumer lag grows

The BisectBatchOnFunctionError option is elegant:

Batch: [good, good, BAD, good, good] ── fails
                    │
        ┌───────────┴───────────┐
        ▼                       ▼
[good, good, BAD]          [good, good] ── succeeds
        │
        │ fails, bisect again
        ▼
   [good, good] ── succeeds

       [BAD] ── fails, exhausts retries, sent to DLQ

This isolates the bad record with logarithmic bisection — much better than failing the entire batch repeatedly.


What You Lose vs. Native Consumers

The serverless abstraction hides complexity but also removes control:

CapabilityNative ConsumerLambda + ESM
Assignment strategyConfigurable (Range, Sticky, Cooperative)No control
Offset commit timingFull controlAfter successful invocation only
Rebalance handlingConsumerRebalanceListener callbacksOpaque
Consumer tuningAll configs availableLimited (batch size, window)
Exactly-onceTransactions availableNot supported
Static membershipConfigurableNot supported
Processing modelContinuous loop, your controlBatch invocation, AWS controlled

When to Use Lambda + ESM

Good fit:

  • Event-driven, stateless processing
  • Variable or bursty traffic patterns
  • Processing time under 15 minutes
  • At-least-once semantics acceptable
  • Team wants minimal infrastructure management
  • Cost optimization for low/medium throughput

Consider self-managed consumers when:

  • Sustained high throughput (millions of messages/hour)
  • Processing takes longer than 15 minutes
  • Exactly-once semantics required
  • Stateful processing (Kafka Streams use cases)
  • Need fine-grained consumer configuration
  • Cold start latency is unacceptable

The Mental Model

Think of it this way:

"AWS runs a Kafka consumer as a managed service. When it receives messages, it calls your function. You don't see the consumer, but all of Kafka's constraints still apply."

The push/pull distinction becomes:

MSK ◄──── PULL ──── ESM ──── PUSH ────► Lambda
(unchanged)       (bridge)          (serverless)

Kafka's model isn't violated. It's wrapped in an abstraction that makes it feel like push — but partition-based parallelism, consumer group semantics, and offset management are all still happening under the hood.


Practical Recommendations

  1. Right-size partitions upfront. Your Lambda parallelism ceiling is your partition count. Over-provision partitions — you can't easily change this later.

  2. Configure batching intentionally. Larger batches = fewer Lambda invocations = lower cost but higher latency. Use BatchSize and MaximumBatchingWindowInSeconds based on your latency requirements.

  3. Enable bisect-on-error. BisectBatchOnFunctionError=true should be your default. It prevents one bad record from blocking a partition.

  4. Set up DLQ from day one. Configure DestinationConfig to send failed records somewhere. You will have failures; make them observable.

  5. Design for at-least-once. Your Lambda will receive duplicates — during retries, during rebalances, during scaling events. Make processing idempotent.

  6. Monitor partition-level lag. CloudWatch metrics show consumer lag. If lag grows, you're either under-partitioned or your Lambda is too slow.

  7. Do the cost math. At some throughput level, Fargate or EKS becomes cheaper than Lambda invocation costs. Know your crossover point.


Conclusion

Lambda + MSK EventSource Mapping is a powerful pattern that brings serverless simplicity to event streaming. But it's not magic — it's a managed Kafka consumer that happens to invoke Lambda.

Understanding the architecture helps you:

  • Avoid the partition-concurrency trap
  • Set realistic expectations for delivery semantics
  • Make informed decisions about when serverless fits and when it doesn't

The abstraction is useful. Just don't let it hide the constraints underneath.


Found this useful? I write about distributed systems, Kafka, and cloud architecture. Follow for more deep-dives that cut through the abstraction layers.

]]>
<![CDATA[Understanding Rust Ownership: The Essentials - 2]]><![CDATA[Learn the essentials of Rust ownership and memory management in our detailed guide.]]>https://srinumadhav.hashnode.dev/understanding-rust-ownership-the-essentials-2https://srinumadhav.hashnode.dev/understanding-rust-ownership-the-essentials-2<![CDATA[references-rust]]><![CDATA[Rust]]><![CDATA[rust-ownership]]><![CDATA[stack and heap]]><![CDATA[srinu madhav vysyaraju]]>Sat, 13 Jul 2024 11:56:04 GMT<![CDATA[

Memory management is a crucial aspect of programming that ensures the efficient use of resources and prevents memory leaks. In Rust, memory management is handled through a unique system of ownership, which comes with a set of rules checked by the compiler. This approach eliminates the need for garbage collection or explicit memory allocation and deallocation, making Rust both safe and efficient.

The Stack and Heap

Understanding the stack and heap is essential in Rust. The stack stores values in a Last-In-First-Out (LIFO) manner, meaning values are pushed and popped in a specific order. The heap, on the other hand, is more flexible but less organized, requiring explicit memory allocation and deallocation.

  • Stack: Fast and efficient for storing values of known size. It follows a strict order for data storage and retrieval, making access times predictable and quick.

  • Heap: Used for dynamically sized data, but accessing it is slower due to the need to follow pointers. Allocation here is more complex, involving searching for available memory space.

When a function is called, its parameters and local variables are pushed onto the stack. Once the function completes, these values are popped off the stack, maintaining the stack's LIFO structure.

Ownership Rules

Rust's ownership system is built on three main rules:

  1. Each value in Rust has a single owner.

  2. There can only be one owner at a time.

  3. When the owner goes out of scope, the value is dropped.

These rules ensure memory safety and prevent data races, making Rust a robust choice for system-level programming.

Variable Scope

Variables in Rust are only valid within a specific scope, which is determined by curly brackets {}.

{
    let s = "hello"; // s is valid from this point forward
    // do stuff with s
} // s is no longer valid here

Scope-based management ensures that memory is automatically cleaned up when it is no longer needed, reducing the risk of memory leaks.

String Type

Strings in Rust are stored on the heap, allowing them to be mutable and growable. This necessitates dynamic memory allocation, which is managed safely by Rust's ownership rules.

let s = String::from("hello");

let mut s = String::from("hello");
s.push_str(", world!"); // Appends a literal to a String
println!("{s}"); // Prints `hello, world!`

Memory and Allocation

Rust automatically deallocates memory when a variable goes out of scope using a function called drop. This eliminates the need for manual memory management and ensures that memory is reclaimed efficiently.

let s1 = String::from("hello");
let s2 = s1; // s1 is no longer valid
let s1 = String::from("hello");
let s2 = s1;

println!("{s1}, world!"); // This will cause a compile-time error

Variables and Data Interacting with Clone

To deeply copy heap data, use the clone method. This is necessary when you want to create an exact duplicate of a value, including the data on the heap.

let s1 = String::from("hello");
let s2 = s1.clone();

println!("s1 = {s1}, s2 = {s2}");

Stack-Only Data: Copy

Simple scalar values like integers are stored on the stack and can be copied quickly. These types implement the Copy trait, allowing for fast and efficient duplication.

let x = 5;
let y = x;

println!("x = {x}, y = {y}"); // x=5, y=5

Ownership and Functions

Passing variables to functions follows the same rules as variable assignments: ownership is moved or copied. This ensures that memory is managed correctly even when data is passed between functions.

fn main() {
    let s = String::from("hello");
    takes_ownership(s); // s is no longer valid here

    let x = 5;
    makes_copy(x); // x is still valid here
}

fn takes_ownership(some_string: String) {
    println!("{some_string}");
}

fn makes_copy(some_integer: i32) {
    println!("{some_integer}");
}

Rust allows returning multiple values using a tuple, providing a flexible way to return data from functions without sacrificing ownership rules.

fn main() {
    let s1 = String::from("hello");
    let (s2, len) = calculate_length(s1);

    println!("The length of '{s2}' is {len}.");
}

fn calculate_length(s: String) -> (String, usize) {
    let length = s.len();
    (s, length)
}

References

References allow you to use values without taking ownership. They are immutable by default, meaning you cannot modify the value they point to. This enables safe borrowing of data.

fn main() {
    let s1 = String::from("hello");
    let len = calculate_length(&s1);

    println!("The length of '{s1}' is {len}.");
}

fn calculate_length(s: &String) -> usize {
    s.len()
}

Mutable References

Mutable references allow modifying the borrowed value but only one mutable reference to a particular piece of data is allowed at a time. This prevents data races and ensures thread safety.

fn main() {
    let mut s = String::from("hello");
    change(&mut s);
}

fn change(some_string: &mut String) {
    some_string.push_str(", world");
}
let mut s = String::from("hello");

let r1 = &mut s;
let r2 = &mut s; // This will cause a compile-time error

To resolve this, create a new scope.

let mut s = String::from("hello");

{
    let r1 = &mut s;
} // r1 goes out of scope here

let r2 = &mut s; // This is now allowed

The Rules of References

  • You can have either one mutable reference or any number of immutable references at any given time.

  • References must always be valid.

These rules ensure that data can be safely accessed and modified without causing undefined behavior.

The Slice Type

Slices let you reference a contiguous sequence of elements in a collection without owning them. They provide a way to work with parts of data structures efficiently.

fn first_word(s: &String) -> usize {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }

    s.len()
}

String Literals as Slices

String literals are stored inside the binary and their type is &str, which is an immutable reference. This makes them efficient and ensures that they can be used safely without additional memory allocation.

fn main() {
    let my_string = String::from("hello world");
    let word = first_word(&my_string[0..6]);
    let word = first_word(&my_string[..]);
    let word = first_word(&my_string);

    let my_string_literal = "hello world";
    let word = first_word(&my_string_literal[0..6]);
    let word = first_word(&my_string_literal[..]);
    let word = first_word(my_string_literal);
}

By understanding Rust's ownership, references, and slices, you can write safe and efficient code that makes the most of your system's memory. This foundational knowledge is crucial for mastering Rust and leveraging its powerful features for system-level programming.

]]>
<![CDATA[Introduction to Rust Basics - 1]]><![CDATA[Learn the fundamentals of Rust programming with our comprehensive guide.Discover how to work with variables, data types, functions, and control flow in…]]>https://srinumadhav.hashnode.dev/introduction-to-rust-basics-1https://srinumadhav.hashnode.dev/introduction-to-rust-basics-1<![CDATA[Rust]]><![CDATA[Rust programming]]><![CDATA[rust lang]]><![CDATA[basics]]><![CDATA[srinu madhav vysyaraju]]>Sat, 13 Jul 2024 11:46:04 GMT<![CDATA[

Rust is a system programming language that emphasizes safety and performance. If you're new to Rust, understanding its core concepts such as variables, data types, functions, and control flow is essential. In this post, we will explore these foundational elements of Rust, providing examples to help you get started.

Variables in Rust

By default, variables in Rust are immutable(cannot change them after declaration). To make a variable mutable, you need to use the mut keyword.

Variable Declaration

Here's how you can declare an immutable variable:

let x: i8 = 5;
println!("The value of x is: {x}");
// x = 6; // This line will cause a compile-time error since `x` is immutable.

To declare a mutable variable, use mut:

let mut x = 5;
println!("The value of x is: {x}");
x = 6;
println!("The value of x is: {x}");

Constants

Constants are always immutable, and you cannot use the mut keyword to make them mutable. Constants are defined using the const keyword and must have their type specified.

const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;

Shadowing

Shadowing allows you to declare a new variable with the same name as a previous variable. This can be useful for transforming a value without needing to create new variable names.

let x = 5;
let x = x + 1; // This does not throw an error; it creates a new variable `x`.
{
    let x = x * 2;
    println!("The value of x in the inner scope is: {x}"); // prints 12
}
println!("The value of x is: {x}"); // prints 6

Shadowing can also change the variable's type:

let spaces = "   "; // String
let spaces = spaces.len(); // Number

In contrast, using mut to change the type of a variable results in an error:

let mut spaces = "   ";
// spaces = spaces.len(); // This will cause a compile-time error

Data Types

Rust has several basic data types that fall into two categories: scalar and compound.

Scalar Data Types

Scalar types represent a single value. Rust has four primary scalar types:

  1. Integers

  2. Floating-point numbers

  3. Booleans

  4. Characters

Integer Types

Integer types can be signed (i.e., they can be negative) or unsigned (i.e., they cannot be negative). Here are some examples:

  • i8, u8 - 8-bit

  • i16, u16 - 16-bit

  • i32, u32 - 32-bit

  • i64, u64 - 64-bit

  • i128, u128 - 128-bit

  • isize, usize - architecture-dependent

Integer literals can be written in various forms:

  • Decimal: 98_222

  • Hex: 0xff

  • Octal: 0o77

  • Binary: 0b1111_0000

  • Byte (u8 only): b'A'

Floating-Point Types

Rust has two floating-point types: f32 and f64:

let x = 2.0; // f64
let y: f32 = 3.0; // f32

Booleans and Characters

Booleans can be either true or false:

let f: bool = false;

Characters are specified using single quotes:

let c = 'z';
let z: char = 'ℤ'; // With explicit type annotation
let heart_eyed_cat = '😻';

Numeric Operations

Rust supports standard numeric operations:

// Addition
let sum = 5 + 10;

// Subtraction
let difference = 95.5 - 4.3;

// Multiplication
let product = 4 * 30;

// Division
let quotient = 56.7 / 32.2;
let truncated = -5 / 3; // Results in -1

// Remainder
let remainder = 43 % 5;

Compound Types

Compound types group multiple values into one type. Rust has two primitive compound types: tuples and arrays.

Tuples

Tuples group different types of values:

let tup: (i32, f64, u8) = (500, 6.4, 1);
let (x, y, z) = tup;
println!("The value of y is: {y}");

let x: (i32, f64, u8) = (500, 6.4, 1);
let five_hundred = x.0;
let six_point_four = x.1;
let one = x.2;

Arrays

Arrays group multiple values of the same type:

let a = [1, 2, 3, 4, 5];

let a: [i32; 5] = [1, 2, 3, 4, 5];

let a = [3; 5]; // [3, 3, 3, 3, 3]

let first = a[0];
let second = a[1];

Accessing an array out of bounds will cause a runtime error.

Functions

Functions in Rust are defined using the fn keyword:

fn print_labeled_measurement(value: i32, unit_label: char) {
    println!("The measurement is: {value}{unit_label}");
}

Statements do not return values, so they cannot be assigned to variables:

fn main() {
    let x = (let y = 6); // This will cause a compile-time error
}

To return a value from a block, ensure the last expression does not have a semicolon:

fn main() {
    let y = {
        let x = 3;
        x + 1 // No semicolon here
    };

    println!("The value of y is: {y}");
}

Control Flow

Rust provides several ways to control the flow of your program.

if Expressions

The if expression allows you to branch your code:

fn main() {
    let number = 6;

    if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }
}

Loops

Rust has three kinds of loops: loop, while, and for.

loop

The loop keyword creates an infinite loop:

fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2; // break exits loop and returns the value
        }
    };

    println!("The result is {result}"); // 20
}

while

The while loop runs while a condition is true:

fn main() {
    let mut number = 3;

    while number != 0 {
        println!("{number}!");

        number -= 1;
    }

    println!("LIFTOFF!!!");
}

for

The for loop iterates over a collection:

fn main() {
    let a = [10, 20, 30, 40, 50];

    for element in a {
        println!("the value is: {element}");
    }
}

fn main2() {
    for number in (1..4).rev() {
        println!("{number}!");
    }
    println!("LIFTOFF!!!");
}

Conclusion

These are the basics of Rust, covering variables, data types, functions, and control flow. Understanding these concepts will provide a strong foundation as you continue to explore the powerful features of Rust. Happy coding!

]]>
<![CDATA[Database Indexing Using Prisma]]><![CDATA[How to enhance query performance using prisma]]>https://srinumadhav.hashnode.dev/database-indexing-using-prismahttps://srinumadhav.hashnode.dev/database-indexing-using-prisma<![CDATA[indexing]]><![CDATA[prisma]]><![CDATA[orm]]><![CDATA[srinu madhav vysyaraju]]>Tue, 07 May 2024 14:25:42 GMT<![CDATA[

Database indexes are a crucial component of modern web applications that depend on databases to store and retrieve data. Indexes can significantly improve the performance of database queries by allowing the database to quickly locate the required data. Prisma, an open-source ORM for Node.js and TypeScript, provides a powerful toolset for managing database indexes. In this blog post, we will explore the benefits of using database indexes and compare the performance of using indexes versus not using indexes using Prisma.

Benefits of Database Indexes Database indexes allow for faster data retrieval by creating a sorted list of data in a specific column or set of columns. Indexes provide several benefits, including:

  1. Faster Query Performance: Indexes can dramatically improve the speed of database queries, especially for large datasets.

  2. Reduced Disk I/O: Indexes reduce the amount of disk I/O required to fetch data by minimizing the number of data pages the database must read.

  3. Improved Data Integrity: Indexes can enforce unique constraints on data, ensuring that no two rows in a table have the same value for a specific column.

  4. Simplified Database Management: Indexes make it easier to organize and manage large datasets by providing quick and easy access to data.

Prisma makes it easy to create indexes on database tables using its intuitive data modelling syntax. Here is an example of how to create an index on a User table's email column using Prisma:

model User {
  id Int @id @default(autoincrement())
  name String
  email String @unique
  age Int?
  @@index([email])
}

In this example, the @@index attribute specifies that an index should be created on the email column of the User table. The @unique attribute ensures that each email address is unique, which is a common requirement for indexing.

Performance Comparison: Indexes vs No Indexes To compare the performance of using indexes versus not using indexes, we will use a simple example of a User table with 10,000 rows. We will run two queries: one with an index on the email column and one without an index.

Query with Index:

const user = await prisma.user.findMany({
  where: {
    email: '[email protected]'
  }
})

Query without Index:

const user = await prisma.user.findMany({
  where: {
    age: 30
  }
})

We will run each query 10 times and record the average query time. Here are the results:

Query TypeAverage Query Time
With Index0.44ms
Without Index4.95ms

As you can see from the results, using an index on the email column dramatically improves the query's performance. The query with an index is over 10 times faster than the query without an index.

Conclusion

Database indexes are a crucial tool for improving the performance of database queries. With Prisma, creating, using, and managing indexes is straightforward and intuitive, making it easy to ensure your database queries are as fast and efficient as possible. By using indexes, you can significantly improve the performance of your application and provide a better user Experience.

]]>