<?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 Carlos Vinícius Tenorio on Medium]]></title>
        <description><![CDATA[Stories by Carlos Vinícius Tenorio on Medium]]></description>
        <link>https://medium.com/@carlosviniciustenorio?source=rss-8a944cc2805d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3wQ7UNtdVe1EKyVOlYLcQQ.jpeg</url>
            <title>Stories by Carlos Vinícius Tenorio on Medium</title>
            <link>https://medium.com/@carlosviniciustenorio?source=rss-8a944cc2805d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 00:53:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@carlosviniciustenorio/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[The Outbox Pattern: Reliable Microservices Messaging]]></title>
            <link>https://medium.com/@carlosviniciustenorio/the-outbox-pattern-reliable-microservices-messaging-ec70a20f4375?source=rss-8a944cc2805d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec70a20f4375</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Carlos Vinícius Tenorio]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 17:14:57 GMT</pubDate>
            <atom:updated>2026-09-08T17:26:05.532Z</atom:updated>
            <content:encoded><![CDATA[<p>In distributed systems, one of the most common problems is ensuring that a <strong>business transaction</strong> and a <strong>message/event</strong> are both processed successfully. If you try to write to a database and publish an event in the same request, you risk one of them failing, leaving your system in an inconsistent state.</p><p>This is where the <strong>Outbox Pattern</strong> comes in.</p><p>In this post, we’ll explore why the Outbox Pattern exists, how it works, and how to implement it in <strong>Go</strong> with practical code examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*HBAqdMXviMF8ERze5VCFnA.jpeg" /></figure><h3><strong>The Problem: Dual Write:</strong></h3><p>Imagine a simple order service. When a customer places an order, we need to:</p><p>1. Save the order to a database.</p><p>2. Publish an `OrderCreated` event to a message broker like Kafka or RabbitMQ.</p><p>A naive implementation might look like this:</p><pre>func (s *OrderService) CreateOrder(ctx context.Context, order Order) error {<br>    if err := s.orderRepo.Save(ctx, order); err != nil {<br>        return err<br>    }<br><br>    if err := s.eventBus.Publish(ctx, OrderCreated{OrderID: order.ID}); err != nil {<br>        return err<br>    }<br><br>    re</pre><p>This works most of the time, but it’s fragile. What happens if the database write succeeds, but the broker is unreachable?</p><ul><li>The order is persisted.</li><li>The event is never published.</li><li>Downstream services never know an order was created.</li></ul><p>Even worse, if we publish first and then the database fails, we emit an event for an order that doesn’t exist.</p><p>This is the <strong>dual write problem</strong>: we are writing to two independent systems inside the same logical operation, and there is no shared atomicity.</p><h4><strong>The Solution: Outbox Pattern</strong></h4><p>The Outbox Pattern solves the dual write problem by <strong>using the same database for both the business transaction and the event</strong>. Instead of publishing directly to the broker, the application stores the event in a dedicated table the <strong>outbox </strong>as part of the same database transaction.</p><p>A separate process, often called the <strong>relay</strong>, periodically reads the outbox table and publishes the events to the message broker.</p><p>The result:</p><ul><li>If the transaction commits, the event is guaranteed to be persisted.</li><li>If the transaction rolls back, the event is never published.</li><li>If publishing to the broker fails, the relay retries until it succeeds.</li></ul><p>This gives us <strong>at-least-once delivery</strong> with strong consistency between state and events.</p><h4><strong>How It Works</strong></h4><p>There are three main steps:</p><p>1. <strong>Write business data and event to the outbox</strong> inside a single transaction.</p><p>2. <strong>Relay reads the outbox table</strong> and publishes events to the broker.</p><p>3. <strong>Relay marks events as published</strong> or deletes them after confirmation.</p><p><strong>Visually:</strong></p><pre>┌──────────────┐<br>│   Service    │<br>└──────┬───────┘<br>       │<br>       ▼<br>┌──────────────┐     ┌─────────────┐<br>│   Database   │────▶│   Outbox    │<br>│  (business   │     │   table     │<br>│    data)     │     └─────────────┘<br>└──────────────┘              │<br>                              │<br>                              ▼<br>                        ┌─────────────┐<br>                        │    Relay    │<br>                        └──────┬──────┘<br>                               │<br>                               ▼<br>                        ┌─────────────┐<br>                        │    Kafka    │<br>                        └─────────────┘</pre><h4><strong>Implementation in Go</strong></h4><p>Let’s implement a minimal but production-style version using Go, PostgreSQL, and a polling-based relay. We’ll assume we have an `orders` table and an `outbox` table.</p><p><strong>Database Schema:</strong></p><pre>CREATE TABLE orders (<br>    id UUID PRIMARY KEY,<br>    customer_id UUID NOT NULL,<br>    amount NUMERIC(10, 2) NOT NULL,<br>    status TEXT NOT NULL,<br>    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()<br>);<br><br>CREATE TABLE outbox (<br>    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),<br>    aggregate_id TEXT NOT NULL,<br>    event_type TEXT NOT NULL,<br>    payload JSONB NOT NULL,<br>    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),<br>    published_at TIMESTAMPTZ<br>);<br><br>CREATE INDEX idx_outbox_unpublished<br>    ON outbox (created_at)<br>    WHERE published_at IS NULL;</pre><p><strong>Event and Outbox Models:</strong></p><pre>package outbox<br><br>import (<br>    &quot;context&quot;<br>    &quot;database/sql&quot;<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)<br><br>type Event struct {<br>    AggregateID string<br>    EventType   string<br>    Payload     any<br>}<br><br>type OrderCreated struct {<br>    OrderID    string  `json:&quot;order_id&quot;`<br>    CustomerID string  `json:&quot;customer_id&quot;`<br>    Amount     float64 `json:&quot;amount&quot;`<br>}</pre><p><strong>Storing the Event in the Outbox:</strong></p><p>The critical detail: the order and the event must be written in the <strong>same transaction</strong>.</p><pre>package order<br><br>import (<br>    &quot;context&quot;<br>    &quot;database/sql&quot;<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;<br>)<br><br>type Repository struct {<br>    db *sql.DB<br>}<br><br>func NewRepository(db *sql.DB) *Repository {<br>    return &amp;Repository{db: db}<br>}<br><br>type Order struct {<br>    ID         string<br>    CustomerID string<br>    Amount     float64<br>    Status     string<br>}<br><br>func (r *Repository) Create(ctx context.Context, order Order) error {<br>    tx, err := r.db.BeginTx(ctx, nil)<br>    if err != nil {<br>        return err<br>    }<br>    defer tx.Rollback()<br><br>    _, err = tx.ExecContext(ctx,<br>        `INSERT INTO orders (id, customer_id, amount, status)<br>         VALUES ($1, $2, $3, $4)`,<br>        order.ID, order.CustomerID, order.Amount, order.Status,<br>    )<br>    if err != nil {<br>        return fmt.Errorf(&quot;insert order: %w&quot;, err)<br>    }<br><br>    payload, err := json.Marshal(order)<br>    if err != nil {<br>        return fmt.Errorf(&quot;marshal payload: %w&quot;, err)<br>    }<br><br>    _, err = tx.ExecContext(ctx,<br>        `INSERT INTO outbox (aggregate_id, event_type, payload)<br>         VALUES ($1, $2, $3)`,<br>        order.ID, &quot;OrderCreated&quot;, payload,<br>    )<br>    if err != nil {<br>        return fmt.Errorf(&quot;insert outbox: %w&quot;, err)<br>    }<br><br>    return tx.Commit()<br>}</pre><p>Because both inserts happen in one transaction, they succeed or fail together. There is no dual write anymore, just one commit to the database.</p><h4><strong>The Relay:</strong></h4><p>The relay is a background process that polls the `outbox` table for unpublished events, publishes them to the broker, and marks them as published.</p><pre>package outbox<br><br>import (<br>    &quot;context&quot;<br>    &quot;database/sql&quot;<br>    &quot;encoding/json&quot;<br>    &quot;fmt&quot;<br>    &quot;log/slog&quot;<br>    &quot;time&quot;<br>)<br><br>type Publisher interface {<br>    Publish(ctx context.Context, topic string, payload []byte) error<br>}<br><br>type Relay struct {<br>    db        *sql.DB<br>    publisher Publisher<br>    interval  time.Duration<br>    batchSize int<br>}<br><br>func NewRelay(db *sql.DB, publisher Publisher, interval time.Duration, batchSize int) *Relay {<br>    return &amp;Relay{<br>        db:        db,<br>        publisher: publisher,<br>        interval:  interval,<br>        batchSize: batchSize,<br>    }<br>}<br><br>func (r *Relay) Run(ctx context.Context) error {<br>    ticker := time.NewTicker(r.interval)<br>    defer ticker.Stop()<br><br>    for {<br>        select {<br>        case &lt;-ctx.Done():<br>            return ctx.Err()<br>        case &lt;-ticker.C:<br>            if err := r.pollAndPublish(ctx); err != nil {<br>                slog.Error(&quot;relay poll failed&quot;, &quot;error&quot;, err)<br>            }<br>        }<br>    }<br>}<br><br>func (r *Relay) pollAndPublish(ctx context.Context) error {<br>    rows, err := r.db.QueryContext(ctx,<br>        `SELECT id, aggregate_id, event_type, payload<br>         FROM outbox<br>         WHERE published_at IS NULL<br>         ORDER BY created_at<br>         LIMIT $1<br>         FOR UPDATE SKIP LOCKED`,<br>        r.batchSize,<br>    )<br>    if err != nil {<br>        return err<br>    }<br>    defer rows.Close()<br><br>    for rows.Next() {<br>        var id, aggregateID, eventType string<br>        var payload []byte<br><br>        if err := rows.Scan(&amp;id, &amp;aggregateID, &amp;eventType, &amp;payload); err != nil {<br>            return err<br>        }<br><br>        if err := r.publisher.Publish(ctx, eventType, payload); err != nil {<br>            return fmt.Errorf(&quot;publish event %s: %w&quot;, id, err)<br>        }<br><br>        if err := r.markPublished(ctx, id); err != nil {<br>            return fmt.Errorf(&quot;mark published %s: %w&quot;, id, err)<br>        }<br>    }<br><br>    return rows.Err()<br>}<br><br>func (r *Relay) markPublished(ctx context.Context, id string) error {<br>    _, err := r.db.ExecContext(ctx,<br>        `UPDATE outbox SET published_at = NOW() WHERE id = $1`,<br>        id,<br>    )<br>    return err<br>}</pre><h4><strong>Key Implementation Details:</strong></h4><ul><li><strong>`FOR UPDATE SKIP LOCKED`</strong>: This prevents multiple relay instances from stepping on each other. Each instance skips rows already locked by another.</li><li><strong>One event at a time per row</strong>: We publish and then mark as published. If the mark fails, the event will be published again on the next poll.</li><li><strong>Polling is simple and portable</strong>: For higher throughput, you can use PostgreSQL `LISTEN/NOTIFY`, Debezium, or a WAL-based change data capture (CDC) tool.</li></ul><h4><strong>At-Least-Once Delivery and Idempotency:</strong></h4><p>The Outbox Pattern guarantees <strong>at-least-once delivery</strong>, not exactly-once. Events can be published more than once due to retries, crashes, or network timeouts.</p><p>That means consumers must be <strong>idempotent</strong>: processing the same event twice should not change the final state.</p><p>A simple way to achieve idempotency is to track processed event IDs:</p><pre>func (c *Consumer) HandleOrderCreated(ctx context.Context, event Event) error {<br>    var payload OrderCreated<br>    if err := json.Unmarshal(event.Payload, &amp;payload); err != nil {<br>        return err<br>    }<br><br>    if err := c.idempotencyStore.Mark(ctx, event.ID); err != nil {<br>        return err<br>    }<br><br>    // ... business logic<br>    return nil<br>}</pre><h4><strong>Tradeoffs:</strong></h4><pre>| Pros | Cons |<br>|------|------|<br>| Strong consistency between DB and events | Events are delivered asynchronously |<br>| Simple to implement with existing database | Requires a relay process |<br>| No additional distributed transactions | Consumers must be idempotent |<br>| Works with any message broker | Outbox table can grow; needs cleanup |<br>| Easy to observe and replay events | Adds slight latency to event delivery |</pre><h4><strong>When to Use the Outbox Pattern:</strong></h4><p>Use it when:</p><ul><li>You need to publish domain events after a business transaction.</li><li>You want to avoid distributed transaction coordinators (like 2PC).</li><li>You already use a relational database as the source of truth.</li><li>Eventual consistency is acceptable for downstream consumers.</li></ul><p>You might <strong>not</strong> need it if:</p><ul><li>You can tolerate occasional inconsistency.</li><li>You are using a database with built-in change streams (e.g., DynamoDB Streams, MongoDB Change Streams) and can consume directly from the WAL.</li></ul><p>The Outbox Pattern is one of the most reliable ways to keep your database and messaging infrastructure in sync. By storing events in the same transaction as your business data, you eliminate the dual write problem and gain a durable, retryable, and observable event pipeline.</p><p>In Go, a few well-placed `sql.Tx` calls and a background relay are enough to implement it safely. From there, you can evolve into CDC-based systems like <strong>Debezium</strong> for higher throughput.</p><p>If you are building microservices in Go and want a pragmatic, transactional event flow, the Outbox Pattern is a great place to start.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec70a20f4375" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retry with Jitter: Why Your Backoff Needs a Little Chaos]]></title>
            <link>https://medium.com/@carlosviniciustenorio/retry-with-jitter-why-your-backoff-needs-a-little-chaos-dd616b2730b7?source=rss-8a944cc2805d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd616b2730b7</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[exponential-backoff]]></category>
            <category><![CDATA[jitter]]></category>
            <dc:creator><![CDATA[Carlos Vinícius Tenorio]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 20:41:07 GMT</pubDate>
            <atom:updated>2026-08-13T20:41:07.029Z</atom:updated>
            <content:encoded><![CDATA[<p>When a service starts failing, the natural reaction of most systems is simple: “try again.” But what happens when <em>*every*</em> client tries again at the exact same time? A recovery mechanism becomes a second attack on the system itself. That is where <strong>jitter</strong> comes in.</p><p>In this article, we will see why a plain retry is not enough, how backoff helps, and why adding jitter can be the difference between a system that heals itself and one that collapses again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*etPa64iCKxr3dYsV.png" /></figure><p><strong>The Problem: Failures Are Not Uniform</strong></p><p>Imagine a database under heavy load. It starts rejecting some requests with timeouts. Your services, all configured with 3 retries and a 1-second delay, behave like this:</p><p>1. A request fails.</p><p>2. Everyone waits exactly 1 second.</p><p>3. Everyone resends at the same time.</p><p>4. The database, already under pressure, receives a new synchronized wave of requests.</p><p>5. It fails again.</p><p>6. Everyone waits exactly 2 seconds.</p><p>7. The same wave repeats.</p><p>This phenomenon is called the <strong>thundering herd</strong>: a group of clients that behaves in a synchronized way and amplifies the failure it was trying to overcome. Retry, by itself, becomes part of the problem.</p><h3><strong>Backoff: The First Line of Defense</strong></h3><p>The first improvement is to introduce a <strong>backoff</strong>, i.e., increase the waiting time between attempts. The most common form is <strong>exponential backoff</strong>:</p><pre>interval = base * 2^attempt<br><br>Example with a 100ms base:<br><br>| Attempt | Interval |<br>|---------|----------|<br>| 1       | 200ms    |<br>| 2       | 400ms    |<br>| 3       | 800ms    |<br>| 4       | 1.6s     |</pre><p>This helps a lot: clients that fail at slightly different moments will wait for increasing intervals. But there is still a problem: clients that fail <strong>almost at the same time</strong> will wait <strong>exactly the same interval</strong>. If 1000 services restart together at attempt 3, 800ms later there is another avalanche.</p><h3><strong>Jitter: Randomness With a Purpose</strong></h3><p><strong>Jitter</strong> is the addition of random variation to the backoff wait time. The goal is not to make the system slower, but to <strong>discourage accidental synchronization</strong> between clients.</p><p>Instead of everyone waiting 800ms, each client waits a random value between 0 and 800ms, for example. The load spreads out over time, and the system has a chance to recover.</p><p>There are several jitter strategies. The three best known are:</p><h3><strong>Full jitter</strong></h3><p>The wait time is a random value between 0 and the calculated backoff.</p><pre>delay = random(0, base * 2^attempt)</pre><p>Simple, but it can produce very short delays, causing attempts to cluster too close together.</p><h3><strong>Equal jitter</strong></h3><p>Split the calculated time in half and add random noise to the other half.</p><pre>base = base * 2^attempt<br>base = base / 2<br>delay = base + random(0, base)</pre><p>More predictable than full jitter, but still spreads clients out well.</p><h3><strong>Decorrelated jitter</strong></h3><p>At each attempt, the new interval is a random value between the previous jitter and a multiplied maximum. This approach tends to keep the chaos alive longer and avoids a sudden drop in the interval.</p><pre>delay = random(base, previous_delay * 3)</pre><h4>Here is a simple implementation of retry with exponential backoff and full jitter in Go.</h4><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;math/rand&quot;<br> &quot;time&quot;<br>)<br><br><br>type Operation func() error<br><br>func Retry(ctx context.Context, op Operation, max int, baseDelay time.Duration) error {<br> var err error<br><br> for attempt := 1; attempt &lt;= max; attempt++ {<br>  err = op()<br>  if err == nil {<br>   return nil<br>  }<br><br>  if attempt == max {<br>   break<br>  }<br><br>  delay := baseDelay * (1 &lt;&lt; (attempt - 1))<br>  if delay &gt; 30*time.Second {<br>   delay = 30 * time.Second<br>  }<br><br>  if delay &gt; 0 {<br>   delay = time.Duration(rand.Int63n(int64(delay)))<br>  }<br><br>  select {<br>  case &lt;-time.After(delay):<br>  case &lt;-ctx.Done():<br>   return ctx.Err()<br>  }<br> }<br><br> return fmt.Errorf(&quot;failed after %d attempts: %w&quot;, max, err)<br>}<br><br>func main() {<br> op := func() error {<br>  return fmt.Errorf(&quot;connection refused&quot;)<br> }<br><br> err := Retry(context.Background(), op, 5, 100*time.Millisecond)<br> if err != nil {<br>  fmt.Println(err)<br> }<br>}</pre><h3><strong>When to Use Jitter</strong></h3><p><strong>Use jitter whenever:</strong></p><ul><li>Multiple clients or instances may fail at the same time.</li><li>The failure is transient and likely caused by server pressure.</li><li>You want to avoid synchronized load spikes after an outage.</li><li>- You integrate with APIs, queues, databases, or shared caches.</li></ul><h3><strong>Best Practices</strong></h3><p>1. <strong>Set a cap for the backoff.</strong> Uncapped exponential backoff can make a client wait minutes or hours.</p><p>2. <strong>Use context for cancellation.</strong> A client may want to abort the retry if the original request already timed out.</p><p>3. <strong>Separate retriable from non-retriable errors.</strong> Errors like 401 Unauthorized or 404 Not Found usually do not improve with retry. 429 Too Many Requests and 5xx errors usually do.</p><p>4. <strong>Consider a circuit breaker.</strong> Retry helps with transient failures. A circuit breaker protects when a service is clearly degraded for a longer period.</p><p>5. <strong>Log the attempts. </strong>Log the attempt number, error, and wait time. It helps a lot when debugging.</p><h3><strong>Summary</strong></h3><ul><li><strong>Retry</strong> means trying again.</li><li><strong>Backoff</strong> means waiting longer each time.</li><li><strong>Jitter</strong> means adding random variation so not all clients try again at once.</li></ul><h4>Together, they form a simple, effective, and essential resilience strategy for distributed systems. If your retry is still deterministic, it may be helping to bring down the very service it was supposed to protect.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd616b2730b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idempotency in Kafka-Based Microservices: Practical Challenges and Strategies]]></title>
            <link>https://medium.com/@carlosviniciustenorio/idempotency-in-kafka-based-microservices-practical-challenges-and-strategies-088d575df435?source=rss-8a944cc2805d------2</link>
            <guid isPermaLink="false">https://medium.com/p/088d575df435</guid>
            <category><![CDATA[deduplication]]></category>
            <category><![CDATA[idempotency]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[Carlos Vinícius Tenorio]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 01:04:28 GMT</pubDate>
            <atom:updated>2026-08-02T01:05:26.387Z</atom:updated>
            <content:encoded><![CDATA[<p>Building microservices around Apache Kafka is straightforward until you start caring about <strong>exactly what happens when a message is processed more than once</strong>. Kafka provides strong delivery guarantees, but it does not magically make your services idempotent. This article explores the practical challenges of guaranteeing idempotency in Kafka-based microservices and concrete strategies to solve them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*gNGqfO_Bn8C2I7VwmQwDyg.png" /></figure><h3><strong>The Problem: Kafka Delivers At-Least-Once by Default</strong></h3><p>Kafka consumers typically work with an <strong>at-least-once delivery</strong> model. The consumer processes a batch of records and then commits the offset. If the application crashes after processing but before the commit, the same records will be delivered again.</p><p>This means every consumer must be prepared to handle the same message more than once.</p><p><strong>Idempotency is not about preventing duplicate delivery. It is about ensuring that duplicate processing does not corrupt the system state.</strong></p><h4><strong>Why `enable.idempotency` Is Not Enough</strong></h4><p>Kafka producers can be configured with `enable.idempotency=true`. This is important, but it only solves a narrow problem.</p><h4><strong>What producer idempotency actually does</strong></h4><p>It ensures that retries from the <strong>same producer session</strong> do not result in duplicate records on the same partition.</p><p>Example:</p><pre>Producer -&gt; sends record<br>Broker -&gt; stores it<br>Producer -&gt; does not receive ack (network glitch)<br>Producer -&gt; retries<br>Broker -&gt; recognizes duplicate sequence number and ignores it</pre><p><strong>What it does NOT do</strong></p><p>- It does not deduplicate messages published by <strong>different producer instances</strong>.</p><p>- It does not deduplicate messages that represent the <strong>same business event</strong> but carry different IDs.</p><p>- It does not make the consumer idempotent.</p><p>If a user clicks a “pay” button twice and your system generates two events with two different IDs, `enable.idempotency` will store both.</p><h3><strong>Common Challenges</strong></h3><p><strong>1. Retries and Reprocessing</strong></p><p>Network timeouts and consumer rebalances cause records to be redelivered. A consumer that has already partially processed a record may be asked to process it again.</p><p><strong>2. External Side Effects</strong></p><p>Even if Kafka delivers a message exactly once, your consumer may call external services:</p><p>- Charge a credit card</p><p>- Send an email</p><p>- Book a shipment</p><p>- Emit an invoice</p><p>These actions may not be undoable. Calling them twice is the real problem.</p><p><strong>3. Concurrent Consumers</strong></p><p>In a multi-instance consumer group, two instances may process two copies of the same event if deduplication is not atomic.</p><pre>Instance A -&gt; checks if event was processed -&gt; no<br>Instance B -&gt; checks if event was processed -&gt; no<br>Instance A -&gt; processes event<br>Instance B -&gt; processes event (duplicate!)</pre><p><strong>4. Semantically Duplicate Events</strong></p><p>Sometimes the same business operation produces multiple messages with different IDs.</p><pre>{ &quot;paymentId&quot;: &quot;PAY-001&quot;, &quot;amount&quot;: 100 }<br>{ &quot;paymentId&quot;: &quot;PAY-002&quot;, &quot;amount&quot;: 100 }</pre><p>The consumer sees two different messages. Deduplicating by message ID is useless here. You need business-level idempotency.</p><h3><strong>Strategies to Guarantee Idempotency</strong></h3><p><strong>1. Design Naturally Idempotent Operations</strong></p><p>The simplest and most robust approach is to make the final operation naturally idempotent.</p><p>Instead of:</p><pre>INSERT INTO payments (id, amount, status) VALUES (&#39;PAY-001&#39;, 100, &#39;PAID&#39;);</pre><p>Use an upsert:</p><pre>INSERT INTO payments (id, amount, status)<br>VALUES (&#39;PAY-001&#39;, 100, &#39;PAID&#39;)<br>ON CONFLICT (id) DO UPDATE<br>SET amount = EXCLUDED.amount, status = EXCLUDED.status;</pre><p>Or an idempotent update:</p><pre>UPDATE payments<br>SET status = &#39;PAID&#39;<br>WHERE id = &#39;PAY-001&#39; AND status != &#39;PAID&#39;;</pre><p>No matter how many times this SQL runs, the final state is the same.</p><p><strong>2. Deduplication with a Control Table</strong></p><p>When the operation is not naturally idempotent, store processed event IDs.</p><pre>CREATE TABLE processed_events (<br>    event_id VARCHAR PRIMARY KEY,<br>    processed_at TIMESTAMP NOT NULL<br>);</pre><p>Consumer logic:</p><pre>func consume(ctx context.Context, event PaymentEvent) error {<br>    eventID := event.EventID<br><br>    _, err := db.ExecContext(ctx,<br>        &quot;INSERT INTO processed_events (event_id, processed_at) VALUES ($1, $2)&quot;,<br>        eventID, time.Now())<br>    if err != nil {<br>        if isDuplicate(err) {<br>            log.Printf(&quot;Event %s already processed, skipping&quot;, eventID)<br>            return nil<br>        }<br>        return err<br>    }<br><br>    return processPayment(ctx, event)<br>}</pre><p>The unique constraint on <strong>`event_id`</strong> guarantees that only the first insert succeeds. This pattern is simple and works with most relational databases.</p><p><strong>3. Distributed Lock with Redis</strong></p><p>For multi-instance consumers, a database unique constraint may not be enough to prevent race conditions across services or regions. Redis provides a fast, atomic lock.</p><pre>SET idempotency:evt-abc-123 &quot;processing&quot; NX EX 30</pre><p>- `NX`: only set if the key does not exist.</p><p>- `EX 30`: expire after 30 seconds to avoid stale locks.</p><p>Consumer logic:</p><pre>func handleEvent(ctx context.Context, event Event) error {<br>    key := fmt.Sprintf(&quot;idempotency:%s&quot;, event.ID)<br><br>    ok, err := redisClient.SetNX(ctx, key, &quot;processing&quot;, 30*time.Second).Result()<br>    if err != nil {<br>        return err<br>    }<br>    if !ok {<br>        log.Printf(&quot;Event %s already being processed, skipping&quot;, event.ID)<br>        return nil<br>    }<br><br>    if err := processEvent(event); err != nil {<br>        // Optionally release the lock to allow retry<br>        return err<br>    }<br><br>    // Extend TTL to keep the deduplication window open<br>    redisClient.Expire(ctx, key, 24*time.Hour)<br>    return nil<br>}</pre><p>The lock prevents two instances from processing the same event concurrently. The longer TTL at the end keeps the deduplication window active.</p><p><strong>4. Use a Stable Business Identifier</strong></p><p>Choose the deduplication key carefully. A broker-generated `messageId` is not reliable for retries because retries may produce different IDs.</p><p>Good identifiers:</p><pre>- `paymentId`<br>- `orderId`<br>- `correlationId` generated by the origin application</pre><p>Bad identifiers:</p><pre>- `kafka.offset`<br>- `kafka.partition`<br>- Broker-generated `messageId` (if it changes between retries)</pre><p>The deduplication key must represent the business operation, not the message envelope.</p><p><strong>5. Kafka Transactions for Exactly-Once Semantics</strong></p><p>Kafka supports <strong>exactly-once semantics (EOS)</strong> through transactions. This is useful when the output is another Kafka topic.</p><p>Configuration:</p><pre>config := &amp;kafka.ConfigMap{<br>    &quot;bootstrap.servers&quot;:  &quot;localhost:9092&quot;,<br>    &quot;enable.idempotence&quot;: true,<br>    &quot;transactional.id&quot;:   &quot;payment-producer-1&quot;,<br>}</pre><p>Producer code:</p><pre>producer, err := kafka.NewProducer(config)<br>if err != nil {<br>    return err<br>}<br><br>ctx := context.Background()<br><br>if err := producer.InitTransactions(ctx); err != nil {<br>    return err<br>}<br><br>if err := producer.BeginTransaction(); err != nil {<br>    return err<br>}<br><br>topic := &quot;output-topic&quot;<br>producer.Produce(&amp;kafka.Message{<br>    TopicPartition: kafka.TopicPartition{Topic: &amp;topic, Partition: kafka.PartitionAny},<br>    Value:          []byte(payment),<br>}, nil)<br><br>// offsets come from the consumer; consumer is the *kafka.Consumer instance<br>if err := producer.SendOffsetsToTransaction(ctx, offsets, consumer); err != nil {<br>    producer.AbortTransaction(ctx)<br>    return err<br>}<br><br>if err := producer.CommitTransaction(ctx); err != nil {<br>    producer.AbortTransaction(ctx)<br>    return err<br>}</pre><p>EOS guarantees that data is written to the output topic and offsets are committed together. However, this only covers Kafka-to-Kafka flows. If the consumer writes to a database or calls an external API, additional idempotency logic is still required.</p><p><strong>6. Outbox Pattern</strong></p><p>When a service must update its database and publish an event, the <strong>outbox pattern</strong> helps maintain consistency without distributed transactions.</p><pre>Application:<br>  1. BEGIN TRANSACTION<br>  2. UPDATE orders SET status = &#39;PAID&#39; WHERE id = &#39;ORDER-001&#39;<br>  3. INSERT INTO outbox (topic, payload) VALUES (&#39;payments&#39;, &#39;{...}&#39;)<br>  4. COMMIT<br><br>Outbox publisher:<br>  - Reads outbox table<br>  - Publishes events to Kafka<br>  - Deletes or marks rows as sent</pre><p>The outbox ensures that the event is published if and only if the local transaction commits. Combined with idempotent consumers, this creates a robust end-to-end flow.</p><h3><strong>What About `enable.idempotency` on the Consumer?</strong></h3><p>There is no `enable.idempotency` for consumers. The consumer must implement idempotency itself, either by design or through deduplication.</p><p>Think of it this way:</p><pre>| Layer | Responsibility |<br>|-------|---------------|<br>| Kafka producer with `enable.idempotency` | Avoids duplicate records caused by producer retries |<br>| Kafka transactions | Coordinates writes across Kafka topics and offsets |<br>| Kafka consumer | Must be idempotent or deduplicate incoming messages |<br>| External systems | Must accept idempotent operations or be guarded by deduplication |</pre><h3><strong>Practical Checklist</strong></h3><p>Before deploying a Kafka consumer to production, ask:</p><p>1. What happens if this message is processed twice?</p><p>2. Is the database operation naturally idempotent (`UPSERT`, `UPDATE … WHERE`) ?</p><p>3. Do I have a unique, stable business identifier for deduplication?</p><p>4. Is my deduplication mechanism atomic across instances?</p><p>5. Are external side effects protected (idempotent APIs, deduplication before call) ?</p><p>6. Are offsets committed only after the processing is complete?</p><p>7. Is the deduplication window long enough for my retry and replay scenarios?</p><h3><strong>Conclusion</strong></h3><p>Kafka is a powerful messaging platform, but it does not eliminate the need for careful idempotency design. `enable.idempotency` on the producer is a valuable tool, but it only solves one part of the problem. Real-world systems require idempotency at the consumer level, often through naturally idempotent operations, deduplication tables, distributed locks, and stable business identifiers.</p><p>The safest mental model is: <strong>assume every Kafka message can be delivered more than once, and design your consumers so that this is harmless.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=088d575df435" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAP vs PACELC: The Trade-offs You’re Already Making (Even If You Don’t Notice)]]></title>
            <link>https://medium.com/@carlosviniciustenorio/cap-vs-pacelc-the-trade-offs-youre-already-making-even-if-you-don-t-notice-1874e102916e?source=rss-8a944cc2805d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1874e102916e</guid>
            <category><![CDATA[pacelc-theorem]]></category>
            <category><![CDATA[cap-theorem]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Carlos Vinícius Tenorio]]></dc:creator>
            <pubDate>Thu, 23 Apr 2026 12:11:53 GMT</pubDate>
            <atom:updated>2026-04-23T12:11:53.445Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lDE5xr10cLRE24ZxCFt3Xw.png" /></figure><p>If you work with distributed systems, even indirectly through cloud services you’ve probably heard about CAP theorem. You might also have come across PACELC, which extends CAP in a more practical way.</p><p>But here’s the uncomfortable truth:</p><blockquote><em>You’re making CAP and PACELC trade-offs every day… even if you’re not implementing distributed systems yourself.</em></blockquote><p>This post aims to give you a clear, practical mental model of both concepts without academic overload.</p><h3>The CAP Theorem (What Happens When Things Break)</h3><p>CAP stands for:</p><ul><li><strong>Consistency ©</strong> → every read returns the most recent write</li><li><strong>Availability (A)</strong> → every request gets a response</li><li><strong>Partition Tolerance (P)</strong> → the system continues to operate despite network failures</li></ul><p>The theorem states:</p><blockquote><em>In the presence of a </em><strong><em>network partition</em></strong><em>, you must choose between </em><strong><em>Consistency</em></strong><em> and </em><strong><em>Availability</em></strong><em>.</em></blockquote><h3>The key nuance most people miss</h3><p>CAP only forces a trade-off when a <strong>partition happens</strong>.</p><p>If there is no partition:</p><ul><li>you can have both consistency and availability</li></ul><p>So CAP is really about:</p><blockquote><strong><em>How your system behaves under failure</em></strong></blockquote><h3>Why CAP Alone Is Not Enough</h3><p>In real-world systems:</p><ul><li>partitions are rare (but inevitable)</li><li>most of the time, systems are operating normally</li></ul><p>So the natural question is:</p><p><strong><em>What trade-offs are we making when everything is working fine?</em></strong></p><p>CAP doesn’t answer that. That’s where PACELC comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bjL4rXci_vlNEM0FYEg2BQ.png" /></figure><h3>PACELC (What Happens Even When Things Work)</h3><p>PACELC extends CAP with one crucial idea:</p><blockquote><strong><em>If there is a Partition (P)</em></strong><em> → choose between Availability (A) or Consistency ©<br></em><strong><em>Else (E)</em></strong><em> → choose between Latency (L) or Consistency ©</em></blockquote><p>Let’s break that down:</p><ul><li><strong>P</strong> = failure scenario (network partition)</li><li><strong>E (Else)</strong> = normal operation (no partition)</li></ul><h3>Understanding the “E” in Practice</h3><p>The “E” simply means:</p><blockquote><strong><em>When the system is healthy, what do you optimize for?</em></strong></blockquote><p>Your options:</p><ul><li><strong>Latency (L)</strong> → faster responses, possibly stale data</li><li><strong>Consistency ©</strong> → slower responses, but always correct data</li></ul><h3>Putting It Together</h3><p>A system can be described like this:</p><h3>PA/EL</h3><ul><li><strong>P → A</strong>: During a partition, prioritize availability</li><li><strong>E → L</strong>: Otherwise, prioritize low latency</li></ul><p>Meaning:</p><ul><li>the system stays up even during failures</li><li>responses are fast, but may not always be strongly consistent</li></ul><h3>PC/EC</h3><ul><li><strong>P → C</strong>: During a partition, prioritize consistency</li><li><strong>E → C</strong>: Even when healthy, prioritize consistency</li></ul><p>Meaning:</p><ul><li>the system may reject requests during failures</li><li>responses may be slower, but guarantees are stronger</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4EcZOfRUxPB7cdjet0CFA.png" /></figure><h3>The Reality: You’re Not Building CAP Systems</h3><p>Most engineers today are not implementing:</p><ul><li>replication protocols</li><li>quorum algorithms</li><li>consensus mechanisms</li></ul><p>Cloud providers already did that.</p><p>So what are you doing?</p><blockquote><strong><em>You’re choosing systems that already made those trade-offs</em></strong></blockquote><h3>Where This Shows Up in Your Daily Work</h3><p>Even if you don’t notice it, you’re constantly deciding:</p><h3>1. Read behavior</h3><ul><li>strong consistency vs eventual consistency</li></ul><h3>2. Replication strategy</h3><ul><li>synchronous vs asynchronous</li></ul><h3>3. Failure handling</h3><ul><li>fail fast (consistency) vs degrade gracefully (availability)</li></ul><h3>4. Latency expectations</h3><ul><li>fast responses vs guaranteed correctness</li></ul><h3>The Real Skill (Especially at Senior/Staff Level)</h3><p>Understanding CAP/PACELC is not about memorizing definitions.</p><p>It’s about being able to say:</p><ul><li>“During a failure, this system will stay available but may return stale data”</li><li>“We’re choosing slower writes to guarantee correctness”</li><li>“We accept eventual consistency to keep latency low”</li></ul><p>In other words:</p><blockquote><strong><em>Translating business requirements into distributed system trade-offs</em></strong></blockquote><h3>A Useful Mental Model</h3><p>If you remember nothing else, remember this:</p><blockquote><strong><em>CAP = what happens when things break</em></strong><em><br></em><strong><em>PACELC = how you pay even when things work</em></strong></blockquote><h3>Final Thoughts</h3><p>Distributed systems are not defined by multiple nodes.</p><p>They are defined by one harsh reality:</p><blockquote><strong><em>You cannot trust the network</em></strong></blockquote><p>CAP forces you to decide what to sacrifice during failure.</p><p>PACELC reminds you that even when everything is working, you’re still paying a price — either in latency or consistency.</p><p>And whether you realize it or not, you’re making that choice every day.</p><p>If you’re designing systems on modern cloud platforms, you don’t need to implement these trade-offs from scratch.</p><p>But you absolutely need to understand them.</p><p>Because the system will behave according to those rules — regardless of whether you’re aware of them or not.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1874e102916e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative AI in Practice: Building Intelligent Agents with MCP, LangGraph, and Observability]]></title>
            <link>https://medium.com/@carlosviniciustenorio/ia-generativa-na-pr%C3%A1tica-construindo-agentes-inteligentes-com-mcp-langgraph-e-observabilidade-81521cb9e6f2?source=rss-8a944cc2805d------2</link>
            <guid isPermaLink="false">https://medium.com/p/81521cb9e6f2</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[faiss]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[langfuse]]></category>
            <dc:creator><![CDATA[Carlos Vinícius Tenorio]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 02:43:27 GMT</pubDate>
            <atom:updated>2026-02-01T02:51:20.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVieiaippsHEMHQS3ykIHQ.png" /></figure><p>🔗 Code on GitHub: <a href="https://github.com/carlosviniciustenorio/agents-lang-graph-py">https://github.com/carlosviniciustenorio/agents-lang-graph-py</a></p><p>Most content about Generative AI still lives in the world of prompt engineering and simple chat demos. While useful, that’s not how AI actually works in production systems.</p><p>In real-world applications, AI must <strong>understand intent, plan actions, use tools, execute external operations, validate results, and be observable</strong>.</p><p>In this article, I’ll show a practical approach to building <strong>production-grade AI agents</strong> using a real architecture based on:</p><ul><li>Local LLM with <strong>Ollama + Mistral</strong></li><li>Orchestration with <strong>LangGraph</strong></li><li>Tool integration via <strong>MCP (Model Context Protocol)</strong></li><li>RAG with <strong>FAISS + SentenceTransformers</strong></li><li>Observability with <strong>Langfuse</strong></li></ul><p>This is <strong>engineering AI agents that integrate with real systems</strong>.</p><h3>What is Generative AI in real systems?</h3><p>Generative AI is not just about generating text. In modern architectures, it behaves like a <strong>decision-making orchestrator</strong>:</p><ul><li>Interpreting user intent (Perception)</li><li>Creating action plans (Planning)</li><li>Selecting tools (Tool Discovery)</li><li>Executing external actions (Execution)</li><li>Validating outputs (Validation)</li><li>Retrying until convergence</li></ul><p>This model turns the LLM into a <strong>cognitive agent</strong>, not just a chatbot.</p><h3>Agent Architecture</h3><p>At the core of the system is a <strong>state graph</strong> built with LangGraph, controlling the execution flow.</p><p>Simplified flow:</p><ol><li><strong>Perception</strong> — classifies the user’s intent.</li><li><strong>Planner</strong> — builds a short, actionable plan.</li><li><strong>Tool Discovery</strong> — selects tools via MCP.</li><li><strong>Executor</strong> — calls APIs or RAG.</li><li><strong>Validator</strong> — checks if the result satisfies the request.</li><li><strong>Retry / End</strong> — controls convergence.</li></ol><p>This pattern creates agents that are <strong>predictable, controllable, and observable</strong>.</p><h3>MCP: Letting AI use real tools</h3><p><strong>MCP (Model Context Protocol)</strong> decouples agents from hardcoded integrations. Instead of embedding logic directly in the agent, it:</p><ul><li>Discovers tools dynamically.</li><li>Lets the agent choose what to use.</li><li>Executes calls via JSON-RPC.</li></ul><p>In this project, the agent can:</p><ul><li>Use <strong>RAG</strong> for knowledge search.</li><li>Call an <strong>external REST API for car ads</strong>.</li></ul><p>This turns the AI into a <strong>real client of your systems</strong>, not just a text generator.</p><h3>RAG with FAISS</h3><p>For knowledge queries, the agent uses Retrieval Augmented Generation:</p><ul><li>Documents are chunked intelligently.</li><li>Embeddings are generated with SentenceTransformers.</li><li>Indexed using FAISS.</li><li>Semantic search runs before the LLM responds.</li></ul><p>With this approach, the model no longer relies only on its own parameters it operates over <strong>your application data</strong>.</p><h3>Observability with Langfuse</h3><p>AI in production without observability is a black box.</p><p>With <strong>Langfuse</strong>, you can:</p><ul><li>Trace every agent step.</li><li>Inspect prompts and outputs.</li><li>Measure latency.</li><li>Debug loops and failures.</li></ul><p>This lets you treat AI agents like any distributed system: with <strong>metrics, tracing, and debuggability</strong>.</p><h3>Why does this matter?</h3><p>In practice, companies don’t need chatbots — they need systems that:</p><ul><li>Make decisions.</li><li>Execute actions.</li><li>Use APIs.</li><li>Validate results.</li><li>Integrate with existing platforms.</li></ul><p>Agent-based architectures make AI part of the <strong>product core</strong>, not just an experimental feature.</p><h3>Conclusion</h3><p>Real Generative AI is not about prompts — it’s about <strong>architecture, orchestration, tools, and observability</strong>.</p><p>As a senior software engineer, my focus is applying AI pragmatically: connecting models to real systems with control, traceability, and scalability in mind.</p><p>If you want to move from hype to real AI engineering, this is the path.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81521cb9e6f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Passed the AWS Certified Solutions Architect Professional (SAP-C02) in Just 3 Weeks]]></title>
            <link>https://medium.com/@carlosviniciustenorio/how-i-passed-the-aws-certified-solutions-architect-professional-sap-c02-in-just-3-weeks-ea374b4c06c7?source=rss-8a944cc2805d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea374b4c06c7</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[sapc02-exam]]></category>
            <category><![CDATA[aws-certification]]></category>
            <dc:creator><![CDATA[Carlos Vinícius Tenorio]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 12:28:15 GMT</pubDate>
            <atom:updated>2025-10-26T12:28:15.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*ebdjfp1wNnXRt0BOgk5gnw.jpeg" /></figure><p>A few weeks ago, I achieved something I’d been putting off for a while, I passed the <strong>AWS Certified Solutions Architect Professional (SAP-C02)</strong> exam.</p><p>It wasn’t an easy journey, but it was definitely a rewarding one. I prepared for <strong>three intense weeks</strong>, and I want to share exactly how I approached it — what worked, what didn’t, and how I leveraged <strong>AI</strong> to make the process much faster and more effective.</p><h3>1. Setting the Foundation</h3><p>The first thing I did was to get familiar with the <strong>official AWS documentation</strong>, because I knew this exam wasn’t just about memorization. It’s about <strong>understanding trade-offs, architectures, and design decisions</strong> at a deep level.</p><p>So I focused on reviewing service documentation for the topics I wasn’t fully confident in things like migration strategies, hybrid architectures, cost optimization, and security patterns.</p><h3>2. Leveraging Structured Guidance &amp; Previous Experience</h3><p>I used <strong>Stéphane Maarek’s Udemy </strong><a href="https://www.udemy.com/course/aws-solutions-architect-professional/?srsltid=AfmBOoorP-3phIQ9KApWpdxvE2ZGkOB9d3OChyikz4nuhbmhSoGY8YPz"><strong>course</strong></a> as my main study framework. I didn’t watched the videos due to my key interested in the course was the <strong>course documentation and the </strong><a href="https://www.udemy.com/course/practice-exam-aws-certified-solutions-architect-professional"><strong>practice exams</strong></a>.<br>I also used a valuable resource that a friend of mine created when he took the earlier version of the exam (SAP-C01): his Notion document (see link below). That gave me a head‐start.<br> 🔗 <a href="https://www.notion.so/pablochristian/Solutions-Architect-Professional-SAP-C01-8096987bfbd24dae9e409163e98a046e">Notion: Solutions Architect Professional SAP-C01 — https://www.notion.so/pablochristian/Solutions-Architect-Professional-SAP-C01-8096987bfbd24dae9e409163e98a046e</a></p><p>Then I compared the difference between SAP-C01 and SAP-C02 using the PDF from the same course by Maarek. That helped me focus on what was truly <em>new</em> and different in C02.</p><p>The mock exams were challenging — often harder than the real one — but they forced me to think critically and identify my weak spots. After each test, I didn’t just review the wrong answers; I revisited <strong>why</strong> my reasoning failed, and went back to the AWS docs to fill in the gaps.</p><h3>3. Accelerating with Generative AI</h3><p>This was the first time I seriously used <strong>generative AI</strong> as part of my study process, and it made a huge difference.</p><p>Whenever I didn’t fully understand a scenario or architectural trade-off, I’d ask the AI to:</p><ul><li>simulate real-world use cases</li><li>debate design choices with me</li><li>explain complex services like I was implementing them in production</li></ul><p>It became like having a personal <strong>study partner and technical reviewer</strong> available 24/7. That constant feedback loop helped me internalize the reasoning behind AWS’s best practices, not just memorize facts.</p><h3>4. Reviewing with Intentional Focus</h3><p>In the final week, I shifted gears from learning to <strong>reinforcement</strong>.<br> I revisited every single service covered in the exam blueprint, even the ones I felt comfortable with and made sure I understood:</p><ul><li>When to use it</li><li>Why to use it</li><li>What its limitations are</li></ul><p>This deliberate repetition built confidence and made me calmer on exam day.</p><h3>5. The Exam Day and Takeaways</h3><p>The exam itself was long and mentally demanding, but familiar. Many questions mirrored the complexity of Maarek’s mock tests and the time I spent analyzing “why not the other options” during practice paid off.</p><p>After 3 hours of deep focus, I saw the word <strong>“Congratulations.”</strong></p><p>That single word felt like a validation of not just my technical knowledge, but the <strong>strategy and mindset</strong> behind how I learned.</p><h3>Final Thoughts</h3><p>If you’re preparing for SAP-C02, here’s my biggest advice:</p><ul><li>Don’t just memorize, <strong>understand architecture trade-offs</strong>.</li><li>Use <strong>practice exams strategically</strong> to identify gaps.</li><li>And if you can, use <strong>AI as a learning amplifier</strong> not for shortcuts, but for deeper understanding.</li></ul><p>Three weeks were intense, but with the right focus, structure, and curiosity, it was absolutely achievable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea374b4c06c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build an AWS Lambda Function Using AWS SAM (Serverless Application Model)]]></title>
            <link>https://medium.com/@carlosviniciustenorio/how-to-build-an-aws-lambda-function-using-aws-sam-serverless-application-model-e7f8801d50d9?source=rss-8a944cc2805d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7f8801d50d9</guid>
            <category><![CDATA[serverless-application]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Carlos Vinícius Tenorio]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 21:46:22 GMT</pubDate>
            <atom:updated>2025-10-11T21:46:22.502Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z650ojSsFqouH8mhebp6LQ.png" /></figure><h3>Introduction</h3><p>Serverless computing has transformed the way developers design and deploy applications. Instead of managing infrastructure, you can focus purely on writing code — and AWS Lambda is at the heart of this revolution.</p><p>However, deploying Lambda functions manually through the AWS Console can become tedious and error-prone. That’s where <strong>AWS SAM (Serverless Application Model)</strong> comes in.</p><p>In this article, we’ll explore what AWS SAM is, why it’s powerful, when to use it, and we’ll finish with a hands-on example of deploying a simple Python Lambda function using SAM.</p><h3>What is AWS SAM?</h3><p><strong>AWS SAM (Serverless Application Model)</strong> is an open-source framework developed by AWS that helps you build serverless applications more easily.</p><p>It extends <strong>AWS CloudFormation</strong> with simplified syntax for defining serverless resources like:</p><ul><li>AWS Lambda functions</li><li>Amazon API Gateway APIs</li><li>DynamoDB tables</li><li>Event sources (like S3, SNS, or SQS triggers)</li></ul><p>A SAM template is basically a <strong>CloudFormation YAML file</strong>, but much more concise.</p><h3>Why Use AWS SAM?</h3><p>Here are some of the main benefits:</p><h3>1. Simplified Infrastructure as Code</h3><p>SAM uses a concise syntax (AWS::Serverless::Function) to define Lambda functions and their triggers, making templates shorter and easier to maintain.</p><h3>2. Local Testing and Debugging</h3><p>You can use the <strong>SAM CLI</strong> to run and debug your Lambda locally before deploying it to AWS.</p><pre>sam local invoke<br>sam local start-api</pre><p>This dramatically improves developer productivity.</p><h3>3. Easy Packaging and Deployment</h3><p>SAM automates packaging your code, uploading it to S3, and deploying it using CloudFormation — all in one command:</p><pre>sam deploy --guided</pre><h3>4. CI/CD Friendly</h3><p>SAM integrates easily with AWS CodePipeline, GitHub Actions, and other CI/CD tools, allowing for automated deployments.</p><h3>When Should You Use SAM?</h3><p>Use AWS SAM when:</p><ul><li>You’re developing <strong>serverless backends</strong> using Lambda + API Gateway.</li><li>You want <strong>IaC (Infrastructure as Code)</strong> but with less YAML verbosity.</li><li>You want to <strong>test Lambdas locally</strong> before deploying.</li><li>You’re building <strong>event-driven architectures</strong> (using SQS, SNS, or DynamoDB streams).</li></ul><p>Avoid SAM if:</p><ul><li>You need <strong>multi-cloud</strong> deployment (use Terraform instead).</li><li>You have <strong>non-serverless workloads</strong> (like EC2 or ECS-heavy stacks).</li></ul><h3>Example: Building a Simple Python AWS Lambda with SAM</h3><p>Let’s go step-by-step.</p><h4>1. Install AWS SAM CLI</h4><pre>brew install aws-sam-cli<br># or<br>choco install aws-sam-cli</pre><p>Confirm the installation:</p><pre>sam --version</pre><h4>2. Initialize a New SAM Project</h4><pre>sam init</pre><p>You’ll be prompted for a few things:</p><ul><li><strong>Template source</strong> → AWS Quick Start Templates</li><li><strong>Runtime</strong> → Python 3.12</li><li><strong>Application name</strong> → hello-lambda</li></ul><p>SAM will generate a folder structure like this:</p><pre>hello-lambda/<br>├── README.md<br>├── template.yaml<br>├── hello_world/<br>│   ├── __init__.py<br>│   ├── app.py<br>│   ├── requirements.txt</pre><h4>3. Write Your Lambda Function (app.py)</h4><pre>import json<br><br>def lambda_handler(event, context):<br>    name = event.get(&quot;name&quot;, &quot;World&quot;)<br>    return {<br>        &quot;statusCode&quot;: 200,<br>        &quot;body&quot;: json.dumps({<br>            &quot;message&quot;: f&quot;Hello, {name} from AWS Lambda with SAM!&quot;<br>        })<br>    }</pre><h4>4. Define the SAM Template (template.yaml)</h4><pre>AWSTemplateFormatVersion: &#39;2010-09-09&#39;<br>Transform: AWS::Serverless-2016-10-31<br>Description: Simple AWS Lambda function using AWS SAM<br><br>Resources:<br>  HelloWorldFunction:<br>    Type: AWS::Serverless::Function<br>    Properties:<br>      Handler: app.lambda_handler<br>      Runtime: python3.12<br>      CodeUri: hello_world/<br>      MemorySize: 128<br>      Timeout: 3<br>      Events:<br>        HelloWorldApi:<br>          Type: Api<br>          Properties:<br>            Path: /hello<br>            Method: get</pre><h4>5. Build and Test Locally</h4><pre>sam build<br>sam local start-api</pre><p>Now open your browser at: <a href="http://127.0.0.1:3000/hello">http://127.0.0.1:3000/hello</a></p><p>You should see:</p><pre>{<br>  &quot;message&quot;: &quot;Hello, World from AWS Lambda with SAM!&quot;<br>}</pre><h4>6. Deploy to AWS</h4><p>When you’re ready:</p><pre>sam deploy --guided</pre><p>SAM will ask for:</p><ul><li>Stack name</li><li>AWS Region</li><li>S3 bucket for code uploads</li></ul><p>Once deployed, it will print the <strong>API Gateway endpoint</strong>.<br> You can then test it in production directly:</p><pre>curl https://&lt;your-api-id&gt;.execute-api.&lt;region&gt;.amazonaws.com/Prod/hello</pre><h3>Conclusion</h3><p>AWS SAM is one of the most developer-friendly tools for deploying serverless applications on AWS.<br> It bridges the gap between <strong>code</strong> and <strong>infrastructure</strong>, offering:</p><ul><li>Rapid local testing</li><li>Simple YAML definitions</li><li>CloudFormation-powered deployments</li></ul><p>If you’re building serverless backends, automations, or microservices — <strong>SAM is a must-have in your AWS toolkit.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7f8801d50d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying .NET Applications, MySQL and Adminer in K8s]]></title>
            <link>https://medium.com/@carlosviniciustenorio/deploying-net-applications-mysql-and-adminer-in-k8s-af584809332c?source=rss-8a944cc2805d------2</link>
            <guid isPermaLink="false">https://medium.com/p/af584809332c</guid>
            <dc:creator><![CDATA[Carlos Vinícius Tenorio]]></dc:creator>
            <pubDate>Thu, 11 Apr 2024 20:19:54 GMT</pubDate>
            <atom:updated>2024-04-12T01:07:56.540Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying .NET Applications, MySQL and Adminer in K8s</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*QkuOmIirDLHJ_80YWut5Zw.png" /></figure><h4>Introduction:</h4><p>Are you a .NET developer eager to harness the power of Kubernetes for deploying your applications, but unsure where to start? Enter Minikube — your gateway to the world of Kubernetes without the complexity of managing a full-scale cluster. In this introductory guide, we’ll explore how Minikube enables .NET developers to leverage Kubernetes locally for seamless application deployment and management.</p><p>Kubernetes has rapidly become the go-to platform for deploying, managing, and scaling containerized applications. However, setting up and configuring a Kubernetes cluster can be daunting, especially for developers new to container orchestration. This is where Minikube shines — it provides a lightweight, single-node Kubernetes cluster that runs locally on your machine, making it the perfect tool for learning Kubernetes concepts and experimenting with deployments.</p><p>In this article, we’ll walk through the basics of Kubernetes and demonstrate how Minikube can be used to deploy .NET applications with ease. Whether you’re a seasoned .NET developer looking to level up your skills or a newcomer curious about container orchestration, this guide will equip you with the knowledge and tools you need to get started with Kubernetes using Minikube.</p><p>Let’s embark on our journey into the world of Kubernetes and unlock the full potential of deploying .NET applications!</p><h3>Wich is the benefits?</h3><ul><li>Scalability: Kubernetes enables horizontal scaling of your applications with ease. It can automatically scale your application based on resource usage or predefined metrics, ensuring that your application can handle varying loads efficiently.</li><li>High Availability: Kubernetes provides built-in mechanisms for ensuring high availability of your applications. It can automatically restart failed containers, reschedule them to healthy nodes, and distribute traffic to healthy instances, minimizing downtime and ensuring a consistent user experience.</li><li>Portability: With Kubernetes, you can deploy your applications consistently across different environments, whether it’s on-premises, in the cloud, or even in hybrid or multi-cloud environments. This portability reduces vendor lock-in and provides flexibility in infrastructure choices.</li><li>Resource Efficiency: Kubernetes optimizes resource utilization by packing multiple applications onto the same hardware infrastructure. It intelligently schedules containers based on available resources, maximizing resource utilization and reducing infrastructure costs.</li><li>Self-Healing: Kubernetes continuously monitors the health of your applications and automatically takes corrective actions in case of failures or issues. It can perform automatic rolling updates, rollbacks, and restarts of containers to maintain the desired state of your applications.</li><li>Declarative Configuration: Kubernetes allows you to define the desired state of your applications using declarative configuration files (YAML or JSON). This declarative approach makes it easy to manage and maintain complex application configurations, as well as enabling version control and reproducibility.</li><li>Service Discovery and Load Balancing: Kubernetes provides built-in service discovery and load balancing for your applications. It automatically assigns a stable IP address and DNS name to each service, allowing other services to discover and communicate with them seamlessly.</li><li>Extensibility: Kubernetes is highly extensible and can be customized to fit your specific requirements. You can extend Kubernetes functionality through custom resource definitions (CRDs), operators, and third-party integrations, enabling you to build and operate complex systems efficiently.</li><li>Community and Ecosystem: Kubernetes has a large and vibrant community, backed by major cloud providers, software vendors, and open-source contributors. This rich ecosystem provides access to a wide range of tools, libraries, and best practices, making it easier to adopt and operate Kubernetes in production environments.</li><li>Cost-Effective: By improving resource utilization, automating operations, and providing a standardized platform for application deployment, Kubernetes helps organizations reduce operational costs and increase the ROI of their infrastructure investments.</li></ul><h3>Dependencies</h3><ul><li>Minikube: <a href="https://minikube.sigs.k8s.io/docs/start/">https://minikube.sigs.k8s.io/docs/start/</a></li><li><strong>.NET Web App image in Docker Hub or other Hub of Docker Images</strong></li></ul><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aMV27bG-ZcbqfnjYaAcPHw.png" /></figure><h3>Let’s go configure the yaml file to provider our services</h3><h4>Web Application Deployment and Service</h4><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: web<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: web<br>  template:<br>    metadata:<br>      labels:<br>        app: web<br>    spec:<br>      affinity:<br>        nodeAffinity:<br>          requiredDuringSchedulingIgnoredDuringExecution:<br>            nodeSelectorTerms:<br>              - matchExpressions:<br>                  - key: node-role.kubernetes.io/master<br>                    operator: DoesNotExist<br>      containers:<br>        - name: web<br>          image: yourWebApplicationImageRepository<br>          ports:<br>            - containerPort: 80<br>          env:<br>            - name: ASPNETCORE_ENVIRONMENT<br>              value: Development<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: web<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: web<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 80</pre><p>This YAML defines a deployment called “web” with 2 replicas, each running a container based on the specified image. It exposes the application on port 80 via a LoadBalancer service, making it accessible externally.</p><h4>Mysql Deployment and Service</h4><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: db<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: db<br>  template:<br>    metadata:<br>      labels:<br>        app: db<br>    spec:<br>      affinity:<br>        nodeAffinity:<br>          requiredDuringSchedulingIgnoredDuringExecution:<br>            nodeSelectorTerms:<br>              - matchExpressions:<br>                  - key: node-role.kubernetes.io/master<br>                    operator: DoesNotExist<br>      containers:<br>        - name: db<br>          image: mysql:latest<br>          env:<br>            - name: MYSQL_ROOT_PASSWORD<br>              value: example<br>            - name: MYSQL_DATABASE<br>              value: mydatabase<br>            - name: MYSQL_USER<br>              value: myuser<br>            - name: MYSQL_PASSWORD<br>              value: mypassword<br>          ports:<br>            - containerPort: 3306<br>          volumeMounts:<br>            - name: db-data<br>              mountPath: /var/lib/mysql<br>      volumes:<br>        - name: db-data<br>          emptyDir: {}<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: db<br>spec:<br>  selector:<br>    app: db<br>  ports:<br>    - protocol: TCP<br>      port: 3306<br>      targetPort: 3306</pre><p>This YAML defines a deployment named “db” running a MySQL database. It ensures that the database pod runs on a specific node using nodeSelector. Additionally, it exposes the database service on port 3306.</p><h4>Adminer Deployment and Service</h4><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: adminer<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: adminer<br>  template:<br>    metadata:<br>      labels:<br>        app: adminer<br>    spec:<br>      affinity:<br>        nodeAffinity:<br>          requiredDuringSchedulingIgnoredDuringExecution:<br>            nodeSelectorTerms:<br>              - matchExpressions:<br>                  - key: node-role.kubernetes.io/master<br>                    operator: DoesNotExist<br>      containers:<br>        - name: adminer<br>          image: adminer<br>          ports:<br>            - containerPort: 8080<br><br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: adminer<br>spec:<br>  type: LoadBalancer<br>  selector:<br>    app: adminer<br>  ports:<br>    - protocol: TCP<br>      port: 8080<br>      targetPort: 8080</pre><p>This YAML defines a deployment named “adminer” running Adminer, a database management tool. Similar to the web service, it’s exposed externally via a LoadBalancer service on port 8080.</p><h3>Let’s go do it!</h3><p>Step 1: Start Minikube</p><p>Start Minikube by running the following command in your terminal:</p><pre>minikube start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PUX69ozj2CMCG-sK8XJAeA.png" /></figure><p>Step 2: Apply YAML Configuration</p><p>Save the YAML configuration provided in a file, for example, deployment.yaml. Then, apply the configuration to your Minikube cluster by running the following command:</p><pre>kubectl apply -f deployment.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*EyFbqueEsfUGGYipNb5ReQ.png" /></figure><p>Step 3: Verify Deployments</p><p>Check that the deployments are running correctly by running the following command:</p><pre>kubectl get deployments</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*WpwhCfO0NQwQlgARhD91yg.png" /></figure><p>Step 4: Verify Services</p><p>Check that the services are running correctly by running the following command:</p><pre>kubectl get services</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*1lm8GjFORbAxX41VZdjYFg.png" /></figure><p>Step 5: See the resilience of our application</p><ul><li>When we delete a pod that is orchestrated by Deployment, the deployment will create a new pod to meet the requirement of having 2 replicas</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuOign6QAu2MNOlZRUg1IQ.png" /></figure><p>Step 6: Access Adminer and Import our Database</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_5u7x7XYbMKNazY_m37TdQ.png" /></figure><p>Step 7: Access the WebAPI and do a Request</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ma6mco6YQbCBjkxsE6oHJw.png" /></figure><h3>Conclusion</h3><p>Deploying microservices with Kubernetes, especially in a local development environment like Minikube, offers a streamlined approach to application management and scalability. By leveraging Kubernetes’ powerful features such as service discovery, load balancing, and automatic scaling, developers can focus more on building and iterating their applications without worrying about infrastructure complexities.</p><p>Throughout this guide, we’ve walked through the process of deploying microservices using YAML configurations in Kubernetes. From defining deployments and services to ensuring each service runs on a separate node, we’ve covered the essential steps to get started with Kubernetes in a local environment.</p><p>As you continue your journey with Kubernetes and microservices development, remember to explore additional features and best practices to optimize your deployment workflows. Whether you’re building a small-scale application or a complex distributed system, Kubernetes provides the flexibility and scalability to meet your evolving needs.</p><p>I hope this guide has provided you with valuable insights and practical knowledge to kickstart your Kubernetes journey. Happy deploying!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af584809332c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET + Benchmark]]></title>
            <link>https://medium.com/@carlosviniciustenorio/net-benchmark-0830d7987085?source=rss-8a944cc2805d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0830d7987085</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[benchmark]]></category>
            <dc:creator><![CDATA[Carlos Vinícius Tenorio]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 23:08:58 GMT</pubDate>
            <atom:updated>2023-11-18T18:20:02.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*8fT2DUtThDqMeERl.png" /></figure><h3>Introduction</h3><p>In the dynamic realm of software development, where milliseconds can make a monumental difference, optimizing code for performance is an art. Enter BenchmarkDotNet, a powerful library that transcends traditional profiling, providing developers with a meticulous lens into the performance intricacies of their code.</p><h3>Wich is the benefits?</h3><ol><li>Precision Measurement: BenchmarkDotNet offers a level of granularity that’s second to none. It doesn’t just measure execution time; it dissects it, revealing insights into CPU cycles, memory usage, and other critical metrics. This depth of analysis is invaluable for developers striving for optimal performance.</li><li>Reproducible Results: In the world of benchmarking, consistency is key. BenchmarkDotNet ensures that your performance measurements are reproducible, providing a stable foundation for comparisons and enabling developers to track the impact of optimizations over time.</li><li>Easy Integration: Seamless integration is a hallmark of BenchmarkDotNet. With a simple attribute-based syntax, developers can effortlessly annotate their methods for benchmarking, making the process intuitive and accessible.</li></ol><h3>Dependencies</h3><blockquote><em>.NET:</em></blockquote><p><a href="https://dotnet.microsoft.com/en-us/download">Download .NET (Linux, macOS, and Windows)</a></p><h3>Configuration</h3><blockquote><strong>Create a .NET project</strong></blockquote><p><strong>CLI</strong>: dotnet new webapi -n ProjectName</p><blockquote><strong>Install the package</strong></blockquote><p>BenchmarkDotNet</p><p><strong>.NET CLI:</strong></p><p>dotnet add package BenchmarkDotNet — version 0.13.10</p><p><strong>Package Manager:</strong></p><p>NuGet\Install-Package BenchmarkDotNet -Version 0.13.10</p><p><strong>Package Reference:</strong></p><p>&lt;PackageReference Include=”BenchmarkDotNet” Version=”0.13.10&quot; /&gt;</p><h3>Configure the Application</h3><ol><li>Configure the Benchmark attributes into your desired class to compare the performance</li></ol><pre>[MemoryDiagnoser]<br>    public class BenchMarkDemo<br>    {<br>        [Benchmark]<br>        public string SerializeWithTextJson() =&gt; System.Text.Json.JsonSerializer.Serialize(new<br>        {<br>            Name = &quot;Carlos Vinícius Tenorio&quot;,<br>            Age = 25,<br>            Role = &quot;Software Engineer&quot;<br>        });<br><br>        [Benchmark]<br>        public string SerializeWithNewtonSoftJson() =&gt; JsonConvert.SerializeObject(new<br>        {<br>            Name = &quot;Carlos Vinícius Tenorio&quot;,<br>            Age = 25,<br>            Role = &quot;Software Engineer&quot;<br>        });<br>    }</pre><pre>class Program<br>    {<br>        static void Main(string[] args)<br>        {<br>            var result = BenchmarkRunner.Run&lt;BenchMarkDemo&gt;();<br>        }<br><br>        <br>    }</pre><p>2) Run the application as release</p><pre>dotnet run -c Release</pre><p>3) See the output console</p><p>Now, we can see from our output that serializing an object with the TextJson library is more performant than NewtonSoft.Json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LVq8K_jado8gK9mkP9sTGw.png" /></figure><p>4) You can see the results in some extensions into directory created by BenchmarkDotnet library</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*ZAcU9lI_OZ01Jchnzm6OQQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*832J1jlaab7DDXrQdZBq_A.png" /></figure><h3>Conclusion:</h3><p>In the landscape of performance optimization, BenchmarkDotNet stands as a beacon for developers striving for excellence. It’s more than a library; it’s a companion in the quest for efficiency, providing the tools needed to sculpt code into a finely tuned masterpiece.</p><p>Join us on this expedition into the heart of performance optimization, where BenchmarkDotNet transforms benchmarks into insights and code into poetry. The journey begins now, and the performance gains await.</p><h3>Thank you!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0830d7987085" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET 7 + Redis]]></title>
            <link>https://medium.com/@carlosviniciustenorio/redis-net-7-ee7267c6927c?source=rss-8a944cc2805d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee7267c6927c</guid>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Carlos Vinícius Tenorio]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 15:28:14 GMT</pubDate>
            <atom:updated>2024-04-12T01:03:46.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bsBQ0FjnloVuBmj1" /></figure><h3>Introduction</h3><p>A cache database is generally used to improve the performance and scalability of an application. It is used as an intermediary layer between the application and the main database, temporarily storing frequently accessed data to reduce access latency.</p><h3>Wich is the benefits?</h3><p>1- <strong>Database load reduction</strong></p><p>If your application receives a high volume of frequent reads of the same data, a cache database can help reduce the load on the main database by avoiding repetitive queries. This can improve application response speed.</p><p>2- <strong>Performance improvement</strong></p><p>Accessing data in a cache database is generally faster than in a main database</p><p>3- <strong>Availability and fault tolerance</strong></p><p>In the event of a primary database failure, a cache database can continue serving requests as long as the necessary data is present in cache</p><p>4- <strong>Content personalization:</strong></p><p>If your application needs to provide personalized content for each user, a cache database can be used to temporarily store this information.</p><p>5- <strong>Scalability</strong></p><p>By adding cache layers to your architecture, you can horizontally scale your application</p><h3>Dependencies</h3><blockquote>.NET:</blockquote><p><a href="https://dotnet.microsoft.com/en-us/download">Download .NET (Linux, macOS, and Windows)</a></p><blockquote>Docker CLI:</blockquote><p><a href="https://docs.docker.com/engine/install/ubuntu/#install-using-the-convenience-script">Install Docker Engine on Ubuntu</a></p><h3>Configuration</h3><p>1- <strong>Create a .NET WEB API using the .NET 7 as framework</strong></p><p><strong>CLI</strong>: dotnet new webapi -n ProjectName</p><p>2- <strong>Install the packages:</strong></p><p><strong>StackExchange.Redis</strong></p><p><strong>Microsoft.Extensions.Caching.StackExchangeRedis</strong></p><p><strong>.NET CLI:</strong></p><p>dotnet add package StackExchange.Redis — version 2.6.116</p><p>dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis — version 8.0.0-preview.5.23302.2</p><p><strong>Package Manager:</strong></p><p>NuGet\Install-Package StackExchange.Redis -Version 2.6.116</p><p>NuGet\Install-Package Microsoft.Extensions.Caching.StackExchangeRedis -Version 8.0.0-preview.5.23302.2</p><p><strong>Package Reference:</strong></p><p>&lt;PackageReference Include=”StackExchange.Redis” Version=”2.6.116&quot; /&gt;</p><p>&lt;PackageReference Include=”Microsoft.Extensions.Caching.StackExchangeRedis” Version=”8.0.0-preview.5.23302.2&quot; /&gt;</p><p>3- <strong>Run a Redis image into Docker</strong></p><p><strong>CLI</strong>: docker run -p 6379:6379 redis</p><h3>Configure the Application</h3><p>1)<strong> Configure the Redis service in the .NET application services.</strong></p><pre>builder.Services.AddStackExchangeRedisCache(redis =&gt; <br>{<br>    redis.InstanceName = apiSettings?.Cache.InstanceName;<br>    redis.Configuration = apiSettings?.Cache.Configuration;<br>});</pre><p>Note: Into my application, I used a class who name is ApiSettings to configure and load parameters from appsettings and parameter store from AWS. So, if you don’t do this, you can replace the InstanceName value to your InstanceName desired, and the Configuration to your Redis endpoint, for example: <strong>“localhost:6379”</strong>.</p><p>2)<strong> Create a CacheService class to create the connection and implement methods</strong></p><pre>public sealed class CacheService : ICacheService<br>    {<br>        private readonly ConnectionMultiplexer _connection;<br>        private readonly IDatabase _cache;<br>        private readonly IServer _server;<br>        public CacheService()<br>        {<br>            _connection = ConnectionMultiplexer.Connect(new ConfigurationOptions(){<br>                EndPoints = {&quot;localhost:6379&quot;},<br>                ClientName = &quot;DesiredName&quot;,<br>            });<br><br>            _cache = _connection.GetDatabase();<br>            _server = _connection.GetServer(&quot;localhost:6379&quot;);<br>        }<br><br>        public async Task Add(string key, string value) =&gt; await _cache.StringSetAsync(string.Concat(&quot;CManager:&quot;,key), value);<br>        public async Task&lt;string?&gt; Get(string key) =&gt; await _cache.StringGetAsync(key);<br>        public async Task Remove(string key) =&gt; await _cache.StringGetDeleteAsync(key);<br>    }</pre><p>3) <strong>Create the interface to use the methods from Dependency Injection</strong></p><pre>public interface ICacheService<br>{<br>  Task Add(string key, string value);<br>  Task&lt;string?&gt; Get(string key);<br>  Task Remove(string key);<br>}</pre><p>4) <strong>Configure the dependency injection</strong></p><pre>services.AddSingleton&lt;ICacheService, CacheService&gt;();</pre><p>Note: You can configure as Scoped or Transient if it makes sense</p><h3>Use the ICacheService to manipulate the data into Redis Database</h3><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public class LibraryController : ControllerBase<br>{<br>    private readonly ICacheService _cacheService;<br><br>    public LibraryController(ICacheService cacheService)<br>    {<br>        _cacheService = cacheService;<br>    }<br><br>    [HttpGet]<br>    public async Task&lt;IActionResult&gt; GetByName([FromQuery]string bookName)<br>    {<br>        var bookInCache = await _cacheService.Get(bookName);<br>        if(string.IsNullOrEmpty(bookInCache)){<br>            var bookInDatabase = await _context.GetByNameAsync(bookName);<br>            await _cacheService.Add(Guid.NewGuid().ToString(), bookInDatabase);<br>            return Ok(bookInDatabase);<br>        }<br>        return Ok(bookInCache);<br>    }<br><br>    [HttpPost]<br>    public async Task&lt;IActionResult&gt; Post([FromBody]object book)<br>    {<br>        var bookInDatabase = _context.GetByName(bookName);<br><br>        if(string.IsNullOrEmpty(bookInDatabase)){<br>      await _context.Add(book);<br>            await _cacheService.Add(Guid.NewGuid().ToString(), book);<br>            return Ok();<br>        }<br><br>        return BadRequest(&quot;Book exist in database&quot;);<br>    } <br>}</pre><h4>Visualize the data into Redis</h4><blockquote>Install the Another Redis Desktop Manager</blockquote><p><a href="https://goanother.com/">Another Redis Desktop Manager</a></p><h4>Configure your connection and use the Desktop Application</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*U_TSgv2IJd93AuNX" /></figure><h3>Note:</h3><p><strong>If you desired a method to get all objects from your Redis Database, you can use the method below.</strong></p><pre>public async Task&lt;List&lt;T&gt;&gt; GetAllObjetcts&lt;T&gt;()<br>{<br>  //If do you wan&#39;t get all objects from a directory, use the searchPattern. <br>  // Otherwise you can delete this pattern.<br>    string searchPattern = &quot;*DirectoryName*&quot;;<br>    RedisKey[] keys = _server.Keys(pattern: searchPattern).ToArray();<br>    RedisValue[] values = await _connection.StringGetAsync(keys);<br>    List&lt;T&gt; response = new();<br><br>    for (int i = 0; i &lt; keys.Length; i++)<br>    {<br>        RedisValue value = values[i];<br>        response.Add(JsonConvert.DesserializeObject(value));<br>    }<br><br>    return response;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee7267c6927c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>