<?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 Diderot Sielinou on Medium]]></title>
        <description><![CDATA[Stories by Diderot Sielinou on Medium]]></description>
        <link>https://medium.com/@diderotsielinou?source=rss-8b07c70272d8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*bBZipL6boRypygkZ</url>
            <title>Stories by Diderot Sielinou on Medium</title>
            <link>https://medium.com/@diderotsielinou?source=rss-8b07c70272d8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:40:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@diderotsielinou/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[NestJS 11 & Hexagonal Architecture: How I Stopped Writing Code I Couldn’t Test]]></title>
            <link>https://javascript.plainenglish.io/nestjs-11-hexagonal-architecture-how-i-stopped-writing-code-i-couldnt-test-1ee0d504379c?source=rss-8b07c70272d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ee0d504379c</guid>
            <category><![CDATA[hexagonal-architecture]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <dc:creator><![CDATA[Diderot Sielinou]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 12:09:30 GMT</pubDate>
            <atom:updated>2026-09-16T12:50:33.533Z</atom:updated>
            <content:encoded><![CDATA[<p>From spaghetti architecture to an inviolable domain — a technical deep-dive into strict Ports &amp; Adapters implementation on a high-traffic platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x1ns2sQmEyV6Bz01aMPffg.png" /></figure><h3>Introduction — The lie of the “well-organized service”</h3><p>A few years ago, I thought I was writing good NestJS code.</p><p>My modules were split. My controllers were thin. My services did… everything else. Creation, updates, complex queries, sending emails, calling external APIs. Everything lived in UserService, PaymentService, CatalogService.</p><p>The project grew. The services did too.</p><p>Then one day, my tech lead asked me to write a unit test for the rule <em>“a user cannot activate two subscriptions simultaneously”</em>.</p><p>I opened the file. The rule was in there, somewhere, buried between a Drizzle call and a feature flag check. To test it, I needed to mock the repository, mock the config service, mock the cache service, spin up a NestJS context…</p><p><strong>20 minutes of setup to test 5 lines of business logic.</strong></p><p>That’s when I realized my problem wasn’t the size of my services. It was their <strong>coupling</strong>.</p><h3>The real problem: traditional layered architecture couples what shouldn’t be coupled</h3><p>In a classic NestJS architecture, dependencies flow downward:</p><pre>Controller → Service → Repository → Database</pre><p>This model has a fundamental flaw: <strong>business logic depends on infrastructure</strong>.</p><p>Your PaymentService imports DrizzleRepository. Your DrizzleRepository knows the PostgreSQL schema. If PostgreSQL changes, the service changes. If the service changes, the controller changes.</p><p>Worse: to test a business rule (a price calculation, a state transition), you have to instantiate the entire chain. The DB. The cache. The external adapters. You never isolate anything.</p><p>The code becomes what’s known as an <strong>anemic domain model</strong>: classes that only hold data, with no behavior, no invariants. Business logic leaks everywhere — into services, into controllers, sometimes even into DTOs.</p><h3>The revelation: Hexagonal Architecture inverts the dependencies</h3><p>Hexagonal Architecture — also called <strong>Ports &amp; Adapters</strong>, introduced by Alistair Cockburn — establishes a radically different principle:</p><p>The domain is at the center. Everything depends on it. It depends on nothing.</p><p>Picture a hexagon. At the center: your pure business logic. All around it: the outside world (HTTP, databases, message queues, third-party APIs). These external elements communicate with the center through <strong>Ports</strong> (abstract interfaces) and <strong>Adapters</strong> (concrete implementations).</p><p><strong>The gaming console metaphor:</strong> your console (the domain) defines a connector standard (the Port). Any compatible controller (the Adapter) can plug in — PlayStation, Xbox, custom. The console doesn’t know which controller is plugged in. It only knows it respects the contract.</p><p>In code: your ActivateSubscriptionUseCase doesn&#39;t know whether behind SubscriptionRepositoryPort sits PostgreSQL, MongoDB, or an in-memory array for tests. It doesn&#39;t care. It calls the contract.</p><h3>The concrete structure in NestJS 11</h3><p>Here’s the structure I apply systematically on every module:</p><pre>src/modules/&lt;domain&gt;/<br>  domain/<br>    entities/          ← business objects with invariants<br>    value-objects/     ← enriched primitives (Email, Money, Status…)<br>    ports/             ← interfaces the domain REQUIRES<br>    events/            ← what happened (past tense, immutable)<br>    errors/            ← typed domain errors<br>  application/<br>    use-cases/         ← 1 file = 1 business verb<br>    services/          ← multi-use-case orchestration if needed<br>    ports/             ← interfaces to the outside (EventBus, Clock…)<br>  infrastructure/<br>    persistence/       ← DB adapters (Drizzle, Prisma…)<br>    cache/             ← Redis adapters<br>    queue/             ← BullMQ adapters<br>    external/          ← third-party API clients<br>  interface/<br>    http/<br>      controllers/     ← receive, delegate, respond<br>      dto/             ← HTTP contract (input/output)<br>      mappers/         ← DTO ↔ Domain<br>  &lt;domain&gt;.module.ts   ← NestJS wiring</pre><p><strong>The golden rule:</strong></p><pre>interface  →  application  →  domain<br>                  ↑               ↓<br>              infrastructure  ←───┘ (implements the ports)</pre><p>domain/ never imports @nestjs/*, never imports Drizzle, never imports Axios. Ever.</p><h3>Deep dive — the 3 key building blocks</h3><h3>Block 1 — The Port (interface + Symbol token)</h3><pre>// domain/ports/subscription-repository.port.ts<br><br>// Symbol guarantees uniqueness — no collision between modules<br>export const SUBSCRIPTION_REPOSITORY = Symbol(&#39;SubscriptionRepository&#39;);<br><br>// The interface = the contract the domain REQUIRES<br>// It doesn&#39;t know if behind it is Postgres, Redis or a mock<br>export interface SubscriptionRepositoryPort {<br>  findById(id: string): Promise&lt;Subscription | null&gt;;<br>  findByPaymentIntentId(paymentIntentId: string): Promise&lt;Subscription | null&gt;;<br>  save(subscription: Subscription): Promise&lt;void&gt;;<br>}</pre><p>Why Symbol instead of a string? A Symbol(&#39;SubscriptionRepository&#39;) is <strong>guaranteed unique in memory</strong>. Two modules using the same string &#39;SubscriptionRepository&#39; as a NestJS token will collide. The Symbol makes that impossible.</p><h3>Block 2 — The Business Entity (invariants + Result pattern)</h3><pre>// domain/entities/subscription.entity.ts<br><br>// The Result type — making errors explicit and typed<br>// No surprise throws: the caller MUST handle both cases<br>type Result&lt;T, E&gt; =<br>  | { ok: true; value: T }<br>  | { ok: false; error: E };<br><br>const ok  = &lt;T&gt;(value: T): Result&lt;T, never&gt;  =&gt; ({ ok: true, value });<br>const err = &lt;E&gt;(error: E): Result&lt;never, E&gt;  =&gt; ({ ok: false, error });<br><br>export class Subscription {<br>  // PRIVATE constructor — impossible to create invalid state with `new`<br>  private constructor(<br>    readonly id: string,<br>    readonly userId: string,<br>    private _status: &#39;pending&#39; | &#39;active&#39; | &#39;canceled&#39; | &#39;expired&#39;,<br>    private _currentPeriod: SubscriptionPeriod | null,<br>    readonly createdAt: Date,<br>  ) {}<br><br>  // Static factory — the only valid entry point to create an entity<br>  static create(id: string, userId: string): Subscription {<br>    return new Subscription(id, userId, &#39;pending&#39;, null, new Date());<br>  }<br><br>  // Reconstruction from persistence<br>  static fromPersistence(row: SubscriptionRow): Subscription {<br>    return new Subscription(<br>      row.id, row.userId, row.status,<br>      row.periodStart &amp;&amp; row.periodEnd<br>        ? SubscriptionPeriod.create(row.periodStart, row.periodEnd)<br>        : null,<br>      row.createdAt,<br>    );<br>  }<br><br>  get status() { return this._status; }<br>  get currentPeriod() { return this._currentPeriod; }<br><br>  // Business method with explicit invariants<br>  activate(<br>    period: SubscriptionPeriod,<br>  ): Result&lt;void, AlreadyActiveError | InvalidTransitionError&gt; {<br><br>    // Invariant 1: idempotence<br>    if (this._status === &#39;active&#39;)<br>      return err(new AlreadyActiveError(this.id));<br><br>    // Invariant 2: legal transition<br>    if (this._status === &#39;canceled&#39; || this._status === &#39;expired&#39;)<br>      return err(new InvalidTransitionError(this._status, &#39;active&#39;));<br><br>    // Controlled mutation — only through this method<br>    this._status = &#39;active&#39;;<br>    this._currentPeriod = period;<br><br>    return ok(undefined);<br>  }<br>}</pre><p><strong>What the private constructor + </strong><strong>static create() guarantee:</strong> It is <strong>physically impossible</strong> to create a Subscription in an inconsistent state. The invariant lives in the code, not in a team convention that gets forgotten under pressure.</p><p><strong>What the </strong><strong>Result pattern brings:</strong> Instead of a throw new Error() that can slip through unnoticed, the caller receives an explicit type. TypeScript forces you to check result.ok before accessing result.value. Errors become <strong>first-class citizens</strong> in the type system.</p><h3>Block 3 — The Use-Case (pure orchestration)</h3><pre>// application/use-cases/activate-subscription.use-case.ts<br><br>export interface ActivateSubscriptionCommand {<br>  paymentIntentId: string;<br>  periodStart: Date;<br>  periodEnd: Date;<br>}<br><br>@Injectable()<br>export class ActivateSubscriptionUseCase {<br>  private readonly logger = new Logger(ActivateSubscriptionUseCase.name);<br><br>  constructor(<br>    // Injection by Symbol token — never the concrete class<br>    @Inject(SUBSCRIPTION_REPOSITORY)<br>    private readonly subscriptions: SubscriptionRepositoryPort,<br><br>    @Inject(EVENT_BUS)<br>    private readonly eventBus: EventBusPort,<br>  ) {}<br><br>  async execute(<br>    cmd: ActivateSubscriptionCommand,<br>  ): Promise&lt;Result&lt;{ subscriptionId: string }, DomainError&gt;&gt; {<br><br>    // 1. Fetch the aggregate — no SQL here<br>    const subscription = await this.subscriptions<br>      .findByPaymentIntentId(cmd.paymentIntentId);<br><br>    if (!subscription)<br>      return err(new SubscriptionNotFoundError(cmd.paymentIntentId));<br><br>    // 2. Build the period Value Object<br>    const period = SubscriptionPeriod.create(cmd.periodStart, cmd.periodEnd);<br><br>    // 3. Delegate the BUSINESS RULE to the entity — use-cases don&#39;t write rules<br>    const result = subscription.activate(period);<br><br>    if (!result.ok) {<br>      this.logger.warn({ error: result.error.code }, &#39;Activation skipped&#39;);<br>      return result;<br>    }<br><br>    // 4. Persist via the port — Drizzle doesn&#39;t exist here<br>    await this.subscriptions.save(subscription);<br><br>    // 5. Publish the event AFTER successful persistence — never before<br>    await this.eventBus.publish(<br>      new SubscriptionActivatedEvent(<br>        subscription.id,<br>        subscription.userId,<br>        cmd.periodEnd,<br>      ),<br>    );<br><br>    return ok({ subscriptionId: subscription.id });<br>  }<br>}</pre><p><strong>The use-case contains zero business logic.</strong> It orchestrates. The rule <em>“you can’t activate an already active subscription”</em> lives in subscription.activate(), not here. This separation is what makes the code testable in total isolation.</p><h3>Measurable benefits for the team and the business</h3><h3>1. Instant unit tests with no infrastructure</h3><pre>// ✅ This test runs in &lt; 5ms. Zero DB. Zero NestJS. Zero complex mocks.<br><br>describe(&#39;ActivateSubscriptionUseCase&#39;, () =&gt; {<br>  it(&#39;publishes an event after successful activation&#39;, async () =&gt; {<br>    const sub = Subscription.fromPersistence({<br>      id: &#39;sub_1&#39;, userId: &#39;user_1&#39;, status: &#39;pending&#39;,<br>      periodStart: null, periodEnd: null, createdAt: new Date(),<br>    });<br><br>    const repo: SubscriptionRepositoryPort = {<br>      findById: jest.fn(),<br>      findByPaymentIntentId: jest.fn().mockResolvedValue(sub),<br>      save: jest.fn().mockResolvedValue(undefined),<br>    };<br><br>    const eventBus: EventBusPort = {<br>      publish: jest.fn().mockResolvedValue(undefined),<br>    };<br><br>    // No NestJS TestingModule. No database.<br>    // Just the constructor.<br>    const useCase = new ActivateSubscriptionUseCase(repo, eventBus);<br><br>    const result = await useCase.execute({<br>      paymentIntentId: &#39;pi_123&#39;,<br>      periodStart: new Date(),<br>      periodEnd: new Date(Date.now() + 86400000 * 30),<br>    });<br><br>    expect(result.ok).toBe(true);<br>    expect(eventBus.publish).toHaveBeenCalledWith(<br>      expect.objectContaining({ subscriptionId: &#39;sub_1&#39; }),<br>    );<br>  });<br><br>  it(&#39;is idempotent — does not republish an event if already active&#39;, async () =&gt; {<br>    const sub = Subscription.fromPersistence({<br>      id: &#39;sub_1&#39;, userId: &#39;user_1&#39;, status: &#39;active&#39;,<br>      periodStart: new Date(), periodEnd: new Date(Date.now() + 86400000),<br>      createdAt: new Date(),<br>    });<br><br>    const eventBus: EventBusPort = { publish: jest.fn() };<br>    const useCase = new ActivateSubscriptionUseCase(<br>      {<br>        findById: jest.fn(),<br>        findByPaymentIntentId: jest.fn().mockResolvedValue(sub),<br>        save: jest.fn(),<br>      },<br>      eventBus,<br>    );<br><br>    await useCase.execute({<br>      paymentIntentId: &#39;pi_123&#39;,<br>      periodStart: new Date(),<br>      periodEnd: new Date(),<br>    });<br><br>    // Replayed Stripe webhook → no event republished<br>    expect(eventBus.publish).not.toHaveBeenCalled();<br>  });<br>});</pre><p><strong>What this concretely changes:</strong> the feedback loop goes from “spin up the test database, seed data, wait 30 seconds” to <strong>instantaneous</strong>. On a project with 1500+ tests, that’s the difference between a CI pipeline that takes 8 minutes and one that takes 45 seconds.</p><h3>2. Swappable infrastructure without touching the domain</h3><p>The day the team decides to replace Drizzle with Prisma, or PostgreSQL with another database, only infrastructure/persistence/ changes. The domain, the application layer, the unit tests — <strong>nothing moves</strong>. That&#39;s the dependency inversion promise, delivered.</p><h3>3. Faster onboarding</h3><p>A new developer joining the team can read activate-subscription.use-case.ts and understand exactly what that feature does in 2 minutes. Without knowing Drizzle. Without knowing BullMQ. Without knowing the database schema.</p><p>The code is <strong>self-documenting through its structure</strong>.</p><h3>4. Resilience to framework changes</h3><p>NestJS 12 changes its API? Stripe updates their SDK? The domain doesn’t know. It never did. Only the adapters change.</p><h3>Limitations to know before you start</h3><p>Being honest about the costs is essential.</p><p><strong>Initial verbosity.</strong> Where a classic pattern creates 1 file, hexagonal architecture creates 4–5 (entity, port, use-case, adapter, mapper). It’s an investment, not a debt.</p><p><strong>Learning curve.</strong> The first few weeks, the team struggles with <em>“where does this code go?”</em>. That’s normal. ADRs (Architecture Decision Records) and a documented hexagonal guide resolve 80% of recurring questions.</p><p><strong>Test verbosity.</strong> Manual port mocks can become repetitive. Test factories (builders) solve this elegantly.</p><p><strong>Not suited for every project.</strong> A simple CRUD with 3 tables and a 2-person team probably doesn’t need this level of rigor. Hexagonal architecture shines on complex domains, growing teams, and projects with a multi-year lifespan.</p><h3>Conclusion — Stop the anemic domain model</h3><p>The anemic domain model is comfortable in the short term. Entities with no behavior, services that do everything, tests that boot an entire database. It works. For a while.</p><p>Then business rules multiply. Services balloon. Tests slow down. New developers struggle to find where the subscription activation rule actually lives.</p><p>Hexagonal Architecture is the antidote. Not a silver bullet — a <strong>discipline</strong>. It asks you to invest time in structure to save it massively over time.</p><p>The question isn’t <em>“can I afford this level of rigor?”</em></p><p>It’s <em>“can I afford not to have it in 6 months?”</em></p><p><strong>Further reading:</strong></p><ul><li><em>Implementing Domain-Driven Design</em> — Vaughn Vernon</li><li><em>Clean Architecture</em> — Robert C. Martin</li><li><em>Hexagonal Architecture</em> — Alistair Cockburn (original article, alistair.cockburn.us)</li><li><em>Domain-Driven Design</em> — Eric Evans</li><li>AWS Prescriptive Guidance — <em>Building Hexagonal Architectures on AWS</em></li></ul><p><em>This article reflects real-world experience on a high-traffic streaming platform. The patterns presented are in production.</em></p><h3>Before you go</h3><ul><li>Please take a moment to like the post and follow the writer!</li><li>Did you know that over 400,000 developers share what they’re building, learning, and discovering across our platforms every month? Learn how you can contribute <a href="https://plainenglish.io/write-for-us">here</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ee0d504379c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/nestjs-11-hexagonal-architecture-how-i-stopped-writing-code-i-couldnt-test-1ee0d504379c">NestJS 11 &amp; Hexagonal Architecture: How I Stopped Writing Code I Couldn’t Test</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis and Caching in 2026: How We Built a Video Chat Matching System That Handles 5,000 Users…]]></title>
            <link>https://medium.com/@diderotsielinou/redis-and-caching-in-2026-how-we-built-a-video-chat-matching-system-that-handles-5-000-users-770f1e51721d?source=rss-8b07c70272d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/770f1e51721d</guid>
            <dc:creator><![CDATA[Diderot Sielinou]]></dc:creator>
            <pubDate>Wed, 22 Apr 2026 11:49:45 GMT</pubDate>
            <atom:updated>2026-04-22T11:49:45.323Z</atom:updated>
            <content:encoded><![CDATA[<h3>Redis and Caching in 2026: How We Built a Video Chat Matching System That Handles 5,000 Users Without Breaking</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*UPnzFSoyw5pvG37tAVaC8g.png" /></figure><p>When we launched <strong>Seendr</strong> — a video chat application that connects strangers based on shared interests — we ran into a problem we never anticipated.</p><p>Not a bug. Not a crash. <strong>Slowness.</strong></p><p>Every time a user triggered a match search, the server queried PostgreSQL: the user’s profile, their interest list, users currently online, language filters, region filters — all in real time. For a single user, this took 800ms to 1.2 seconds. With 500 users simultaneously searching for a match, the server went down.</p><p>The solution? <strong>Redis.</strong> Two days of implementation. Result: matching time dropped to under 80ms, database load reduced by 90%, and the application now handles 5,000 simultaneous connections.</p><p>Our stack: <strong>Django</strong> for the REST API, <strong>Django Channels</strong> (via Daphne) for WebSockets, <strong>Celery</strong> for background tasks — and Redis sitting at the center of all three.</p><p>This article is what I wish I had read before starting.</p><h3>Why Redis Became the Core of Seendr</h3><p>On Seendr, Redis plays three roles simultaneously:</p><ol><li><strong>Application cache</strong> — profiles, search results, rankings</li><li><strong>Channel Layer for Django Channels</strong> — WebSocket synchronization across instances</li><li><strong>Celery Broker</strong> — message queue for async tasks (email sending, cleanup, notifications)</li></ol><p>In our docker-compose.yml, Redis is configured like this:</p><pre>redis:<br>  image: redis:7-alpine<br>  command: redis-server --appendonly yes --maxmemory 256mb --maxmemory-policy allkeys-lru<br>  ports:<br>    - &quot;6380:6379&quot;<br>  healthcheck:<br>    test: [&quot;CMD&quot;, &quot;redis-cli&quot;, &quot;ping&quot;]</pre><p>allkeys-lru automatically removes the least recently used keys when Redis reaches 256MB. This is the optimal eviction policy for an application cache.</p><h3>Why Caching Is Non-Negotiable in 2026</h3><p>Teams are smaller. Seendr runs with 3 developers where an equivalent startup would have had 8 people in 2022. Fewer people to optimize queries, monitor performance, and scale infrastructure.</p><p>Caching is today <strong>the optimization with the best effort-to-impact ratio</strong> you can bring to a Django application. A well-placed Redis layer can:</p><ul><li>Reduce PostgreSQL load by 80 to 95%</li><li>Cut your response times by 5 to 10x</li><li>Significantly reduce your cloud bill (every millisecond saved = money on Lambda or serverless)</li></ul><p>In Python/Django job postings in 2026, Redis appears in <strong>more than 30% of senior backend listings</strong>. It is no longer a “nice to have.” It is a baseline skill for anyone building applications that hold up in production.</p><h3>Installing and Configuring Redis in Django</h3><pre>pip install django-redis redis channels channels-redis celery</pre><p>Configuration in settings.py:</p><pre># settings/base.py<br><br>REDIS_URL = env(&quot;REDIS_URL&quot;, default=&quot;redis://localhost:6379/0&quot;)<br><br># ─── Cache ────────────────────────────────────────────────────────────────────<br>CACHES = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;django_redis.cache.RedisCache&quot;,<br>        &quot;LOCATION&quot;: REDIS_URL,<br>        &quot;OPTIONS&quot;: {<br>            &quot;CLIENT_CLASS&quot;: &quot;django_redis.client.DefaultClient&quot;,<br>            &quot;CONNECTION_POOL_KWARGS&quot;: {&quot;max_connections&quot;: 50},<br>            &quot;COMPRESSOR&quot;: &quot;django_redis.compressors.zlib.ZlibCompressor&quot;,<br>        },<br>        &quot;KEY_PREFIX&quot;: &quot;seendr&quot;,<br>        &quot;TIMEOUT&quot;: 300,  # 5 minutes default<br>    }<br>}<br><br># ─── Sessions via Redis ────────────────────────────────────────────────────────<br>SESSION_ENGINE = &quot;django.contrib.sessions.backends.cache&quot;<br>SESSION_CACHE_ALIAS = &quot;default&quot;<br><br># ─── Django Channels (WebSockets) ─────────────────────────────────────────────<br>CHANNEL_LAYERS = {<br>    &quot;default&quot;: {<br>        &quot;BACKEND&quot;: &quot;channels_redis.core.RedisChannelLayer&quot;,<br>        &quot;CONFIG&quot;: {<br>            &quot;hosts&quot;: [REDIS_URL],<br>            &quot;capacity&quot;: 1500,<br>            &quot;expiry&quot;: 10,<br>        },<br>    }<br>}<br><br># ─── Celery (async tasks) ─────────────────────────────────────────────────────<br>CELERY_BROKER_URL = REDIS_URL<br>CELERY_RESULT_BACKEND = REDIS_URL<br>CELERY_ACCEPT_CONTENT = [&quot;json&quot;]<br>CELERY_TASK_SERIALIZER = &quot;json&quot;</pre><p>Three lines of configuration, and Django uses Redis for caching, sessions, and WebSockets.</p><h3>The Seendr Case: Real-Time Matching Without PostgreSQL</h3><p>The original problem: every match attempt caused Django to query PostgreSQL to find available users. In real time. For every user. That is exactly what Redis is built to eliminate.</p><h3>Step 1 — Maintain the Matching Pool in Redis</h3><p>Instead of running SELECT * FROM users WHERE status = &#39;available&#39; on every match request, we keep a live list of available users <strong>directly in Redis</strong>, updated in real time.</p><pre># matching/services.py<br>import json<br>import time<br>from django_redis import get_redis_connection<br><br>redis_client = get_redis_connection(&quot;default&quot;)<br><br><br>def add_user_to_pool(user):<br>    &quot;&quot;&quot;Add a user to the matching pool.&quot;&quot;&quot;<br>    key = f&quot;matching:pool:{user.id}&quot;<br>    payload = {<br>        &quot;user_id&quot;: str(user.id),<br>        &quot;interests&quot;: list(user.interests.values_list(&quot;slug&quot;, flat=True)),<br>        &quot;language&quot;: user.language,<br>        &quot;region&quot;: user.region,<br>        &quot;joined_at&quot;: int(time.time()),<br>    }<br><br>    # Store the full profile as a Redis hash<br>    redis_client.hset(<br>        key,<br>        mapping={<br>            k: json.dumps(v) if isinstance(v, list) else v<br>            for k, v in payload.items()<br>        },<br>    )<br><br>    # TTL of 2 minutes — expires automatically if the user disconnects without notice<br>    redis_client.expire(key, 120)<br><br>    # Index by language for fast filtering<br>    redis_client.sadd(f&quot;matching:lang:{user.language}&quot;, str(user.id))<br>    redis_client.expire(f&quot;matching:lang:{user.language}&quot;, 300)<br><br><br>def remove_user_from_pool(user_id, language):<br>    &quot;&quot;&quot;Remove a user from the matching pool.&quot;&quot;&quot;<br>    redis_client.delete(f&quot;matching:pool:{user_id}&quot;)<br>    redis_client.srem(f&quot;matching:lang:{language}&quot;, str(user_id))<br><br><br>def find_match(seeker_id, interests, language):<br>    &quot;&quot;&quot;Find the best match in Redis — without touching PostgreSQL.&quot;&quot;&quot;<br>    candidates = redis_client.smembers(f&quot;matching:lang:{language}&quot;)<br><br>    best_match = None<br>    best_score = -1<br><br>    for candidate_id in candidates:<br>        candidate_id = candidate_id.decode()<br>        if candidate_id == str(seeker_id):<br>            continue<br><br>        data = redis_client.hgetall(f&quot;matching:pool:{candidate_id}&quot;)<br>        if not data:<br>            continue<br><br>        candidate_interests = json.loads(data.get(b&quot;interests&quot;, b&quot;[]&quot;))<br>        score = len(set(interests) &amp; set(candidate_interests))<br><br>        if score &gt; best_score:<br>            best_score = score<br>            best_match = candidate_id<br><br>    return best_match</pre><p>Result: across 500 available users, this search executes in <strong>under 10ms</strong>. Before, the same logic with PostgreSQL took 800ms.</p><h3>Core Django Caching Patterns with django-redis</h3><h3>Cache-Aside with @cache_page and cache.get/set</h3><p>Django provides several levels of caching. For full views:</p><pre># views/profiles.py<br>from django.views.decorators.cache import cache_page<br>from django.utils.decorators import method_decorator<br>from rest_framework.viewsets import ReadOnlyModelViewSet<br><br><br>@method_decorator(cache_page(60 * 60), name=&quot;dispatch&quot;)  # 1 hour<br>class PublicProfileViewSet(ReadOnlyModelViewSet):<br>    &quot;&quot;&quot;Public profiles rarely change — cache aggressively.&quot;&quot;&quot;<br>    queryset = User.objects.select_related(&quot;profile&quot;).prefetch_related(&quot;interests&quot;)<br>    serializer_class = PublicProfileSerializer</pre><p>For finer-grained control:</p><pre># services/user_service.py<br>from django.core.cache import cache<br><br><br>def get_user_profile(user_id: str) -&gt; dict | None:<br>    cache_key = f&quot;profile:{user_id}&quot;<br><br>    cached = cache.get(cache_key)<br>    if cached is not None:<br>        return cached<br><br>    try:<br>        user = (<br>            User.objects<br>            .select_related(&quot;profile&quot;)<br>            .prefetch_related(&quot;interests&quot;)<br>            .get(id=user_id)<br>        )<br>        data = UserProfileSerializer(user).data<br>        cache.set(cache_key, data, timeout=3600)  # 1 hour<br>        return data<br>    except User.DoesNotExist:<br>        return None<br><br><br>def invalidate_user_profile(user_id: str):<br>    &quot;&quot;&quot;Invalidate the cache after a profile update.&quot;&quot;&quot;<br>    cache.delete(f&quot;profile:{user_id}&quot;)</pre><p>A Custom @cache_result Decorator</p><pre># utils/cache.py<br>import functools<br>import hashlib<br>import json<br>from django.core.cache import cache<br><br><br>def cache_result(timeout=300, prefix=&quot;&quot;):<br>    &quot;&quot;&quot;Decorator to cache a function&#39;s return value.&quot;&quot;&quot;<br>    def decorator(func):<br>        @functools.wraps(func)<br>        def wrapper(*args, **kwargs):<br>            key_data = json.dumps(<br>                {&quot;args&quot;: args, &quot;kwargs&quot;: kwargs}, default=str, sort_keys=True<br>            )<br>            cache_key = f&quot;{prefix or func.__name__}:{hashlib.md5(key_data.encode()).hexdigest()}&quot;<br><br>            result = cache.get(cache_key)<br>            if result is not None:<br>                return result<br><br>            result = func(*args, **kwargs)<br>            if result is not None:<br>                cache.set(cache_key, result, timeout=timeout)<br>            return result<br>        return wrapper<br>    return decorator<br><br><br># Usage<br>@cache_result(timeout=300, prefix=&quot;trending_interests&quot;)<br>def get_trending_interests(limit=10):<br>    return list(<br>        InterestMatch.objects<br>        .values(&quot;interest__slug&quot;)<br>        .annotate(count=Count(&quot;id&quot;))<br>        .order_by(&quot;-count&quot;)[:limit]<br>    )</pre><h3>Cache Warming with Celery Beat</h3><p>Seendr receives 80% of its traffic between 8pm and 11pm. We pre-warm the cache 30 minutes before peak via a scheduled Celery task.</p><pre># tasks/cache_tasks.py<br>from celery import shared_task<br>from django.utils import timezone<br>from datetime import timedelta<br><br><br>@shared_task(name=&quot;warm_matching_cache&quot;)<br>def warm_matching_cache():<br>    &quot;&quot;&quot;Pre-warm the matching pool before peak traffic.&quot;&quot;&quot;<br>    recently_active = User.objects.filter(<br>        last_seen__gte=timezone.now() - timedelta(minutes=15),<br>        is_available=True,<br>    ).prefetch_related(&quot;interests&quot;).select_related(&quot;profile&quot;)<br><br>    count = 0<br>    for user in recently_active:<br>        add_user_to_pool(user)<br>        count += 1<br><br>    return f&quot;Cache warmed: {count} users&quot;</pre><p>In settings.py:</p><pre>CELERY_BEAT_SCHEDULE = {<br>    &quot;warm-matching-cache&quot;: {<br>        &quot;task&quot;: &quot;tasks.cache_tasks.warm_matching_cache&quot;,<br>        &quot;schedule&quot;: crontab(minute=&quot;*/5&quot;),<br>    },<br>}</pre><h3>Django Channels + Redis: WebSockets at Scale</h3><p>This is where Redis becomes truly indispensable. Django Channels uses Redis as a channel layer to synchronize WebSockets across multiple Daphne instances.</p><p>Without Redis, if user A is connected to instance 1 and user B to instance 2, they cannot communicate. With Redis, all instances share the same message bus.</p><pre># consumers/matching_consumer.py<br>import json<br>from channels.generic.websocket import AsyncWebsocketConsumer<br>from channels.db import database_sync_to_async<br>from matching.services import add_user_to_pool, remove_user_from_pool, find_match<br><br><br>class MatchingConsumer(AsyncWebsocketConsumer):<br><br>    async def connect(self):<br>        self.user = self.scope[&quot;user&quot;]<br>        if not self.user.is_authenticated:<br>            await self.close()<br>            return<br><br>        # Join personal group to receive notifications<br>        self.personal_group = f&quot;user_{self.user.id}&quot;<br>        await self.channel_layer.group_add(self.personal_group, self.channel_name)<br><br>        # Add to the matching pool in Redis<br>        await database_sync_to_async(add_user_to_pool)(self.user)<br>        await self.accept()<br><br>    async def disconnect(self, close_code):<br>        await self.channel_layer.group_discard(self.personal_group, self.channel_name)<br>        await database_sync_to_async(remove_user_from_pool)(<br>            self.user.id, self.user.language<br>        )<br><br>    async def receive(self, text_data):<br>        data = json.loads(text_data)<br><br>        if data.get(&quot;action&quot;) == &quot;find_match&quot;:<br>            interests = data.get(&quot;interests&quot;, [])<br>            match_id = await database_sync_to_async(find_match)(<br>                self.user.id, interests, self.user.language<br>            )<br><br>            if match_id:<br>                room_id = (<br>                    f&quot;room_{min(str(self.user.id), match_id)}&quot;<br>                    f&quot;_{max(str(self.user.id), match_id)}&quot;<br>                )<br><br>                # Notify both users via the Redis Channel Layer<br>                for uid in [str(self.user.id), match_id]:<br>                    await self.channel_layer.group_send(<br>                        f&quot;user_{uid}&quot;,<br>                        {<br>                            &quot;type&quot;: &quot;match_found&quot;,<br>                            &quot;room_id&quot;: room_id,<br>                            &quot;partner_id&quot;: (<br>                                match_id if uid == str(self.user.id)<br>                                else str(self.user.id)<br>                            ),<br>                        },<br>                    )<br>            else:<br>                await self.send(json.dumps({&quot;type&quot;: &quot;no_match_found&quot;}))<br><br>    # Handler called when a &quot;match_found&quot; message arrives via Redis<br>    async def match_found(self, event):<br>        await self.send(json.dumps({<br>            &quot;type&quot;: &quot;match_found&quot;,<br>            &quot;room_id&quot;: event[&quot;room_id&quot;],<br>            &quot;partner_id&quot;: event[&quot;partner_id&quot;],<br>        }))</pre><p>group_send publishes through the Redis Channel Layer. All Daphne instances receive the message and deliver it to their connected WebSockets. This is the native Django Channels replacement for manual Redis Pub/Sub.</p><h3>Rate Limiting with Redis</h3><p>On Seendr, a user cannot trigger more than 10 matching attempts per minute. We implement this with a Django middleware and direct Redis access.</p><pre># middleware/rate_limit.py<br>from django.http import JsonResponse<br>from django_redis import get_redis_connection<br><br><br>class RateLimitMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br>        self.redis = get_redis_connection(&quot;default&quot;)<br><br>    def __call__(self, request):<br>        if request.path.startswith(&quot;/api/matching/&quot;):<br>            result = self._check_rate_limit(request)<br>            if result:<br>                return result<br>        return self.get_response(request)<br><br>    def _check_rate_limit(self, request, max_requests=10, window_seconds=60):<br>        user_id = (<br>            request.user.id<br>            if request.user.is_authenticated<br>            else request.META.get(&quot;REMOTE_ADDR&quot;)<br>        )<br>        key = f&quot;ratelimit:{user_id}:{request.path}&quot;<br><br>        current = self.redis.incr(key)<br>        if current == 1:<br>            self.redis.expire(key, window_seconds)<br><br>        if current &gt; max_requests:<br>            return JsonResponse(<br>                {&quot;error&quot;: &quot;Too many requests&quot;, &quot;retry_after&quot;: self.redis.ttl(key)},<br>                status=429,<br>                headers={&quot;X-RateLimit-Remaining&quot;: &quot;0&quot;},<br>            )<br>        return None</pre><p>Or with django-ratelimit, which integrates directly with the Redis cache backend:</p><pre># views/matching.py<br>from django_ratelimit.decorators import ratelimit<br>from django.utils.decorators import method_decorator<br><br><br>@method_decorator(ratelimit(key=&quot;user&quot;, rate=&quot;10/m&quot;, method=&quot;POST&quot;, block=True), name=&quot;post&quot;)<br>class MatchingView(APIView):<br>    def post(self, request):<br>        # ...</pre><p>incr is atomic. Even if 200 requests arrive simultaneously, each one gets a unique counter value. No race condition possible.</p><h3>Redis Sorted Sets — Real-Time Trending</h3><p>On Seendr, we display the most popular interests of the moment. Redis sorted sets maintain this ranking automatically, with no SQL query required.</p><pre># services/trending.py<br>from django_redis import get_redis_connection<br><br>redis_client = get_redis_connection(&quot;default&quot;)<br><br><br>def track_interest_match(interest_slug: str):<br>    &quot;&quot;&quot;Increment an interest&#39;s score on every successful match.&quot;&quot;&quot;<br>    redis_client.zincrby(&quot;trending:interests:daily&quot;, 1, interest_slug)<br><br><br>def get_trending_interests(limit: int = 10) -&gt; list[dict]:<br>    &quot;&quot;&quot;Get the top N interests with their scores.&quot;&quot;&quot;<br>    results = redis_client.zrevrange(<br>        &quot;trending:interests:daily&quot;, 0, limit - 1, withscores=True<br>    )<br>    return [{&quot;slug&quot;: item[0].decode(), &quot;score&quot;: int(item[1])} for item in results]<br><br><br>def get_interest_rank(interest_slug: str) -&gt; int | None:<br>    &quot;&quot;&quot;Get the rank of a given interest in the leaderboard.&quot;&quot;&quot;<br>    rank = redis_client.zrevrank(&quot;trending:interests:daily&quot;, interest_slug)<br>    return rank + 1 if rank is not None else None</pre><pre># Reset the daily leaderboard at midnight<br>@shared_task(name=&quot;reset_daily_trending&quot;)<br>def reset_daily_trending():<br>    redis_client = get_redis_connection(&quot;default&quot;)<br>    redis_client.delete(&quot;trending:interests:daily&quot;)</pre><p>zincrby is atomic. 5,000 users can increment the same interest simultaneously without conflict.</p><h3>Common Mistakes to Avoid</h3><h3>1. keys(&#39;*&#39;) in Production — Real Danger</h3><p>KEYS is a blocking command. On 100,000 keys, it freezes Redis for several seconds and impacts every active user. Always use SCAN.</p><pre># DANGEROUS in production<br>keys = redis_client.keys(&quot;matching:pool:*&quot;)<br><br># Correct approach<br>def scan_keys(pattern: str) -&gt; list[str]:<br>    keys = []<br>    cursor = 0<br>    while True:<br>        cursor, found = redis_client.scan(cursor, match=pattern, count=100)<br>        keys.extend(k.decode() for k in found)<br>        if cursor == 0:<br>            break<br>    return keys</pre><h3>2. Cache Stampede — The Django Mutex Pattern</h3><p>When a popular key expires, hundreds of requests hit the database simultaneously. The solution: a Redis-based mutex.</p><pre># utils/cache.py<br>import time<br>from django.core.cache import cache<br><br><br>def get_or_set_with_lock(cache_key: str, fetch_fn, timeout=300, lock_timeout=10):<br>    &quot;&quot;&quot;Mutex pattern to prevent cache stampede.&quot;&quot;&quot;<br>    cached = cache.get(cache_key)<br>    if cached is not None:<br>        return cached<br><br>    lock_key = f&quot;lock:{cache_key}&quot;<br><br>    # cache.add = set only if the key does not exist<br>    acquired = cache.add(lock_key, &quot;1&quot;, lock_timeout)<br><br>    if acquired:<br>        try:<br>            result = fetch_fn()<br>            if result is not None:<br>                cache.set(cache_key, result, timeout)<br>            return result<br>        finally:<br>            cache.delete(lock_key)<br>    else:<br>        time.sleep(0.1)<br>        return get_or_set_with_lock(cache_key, fetch_fn, timeout, lock_timeout)</pre><p>3. Automatic Cache Invalidation with Django Signals</p><pre># signals.py<br>from django.db.models.signals import post_save<br>from django.dispatch import receiver<br>from django.core.cache import cache<br><br><br>@receiver(post_save, sender=User)<br>def invalidate_user_cache(sender, instance, **kwargs):<br>    cache.delete_many([<br>        f&quot;profile:{instance.id}&quot;,<br>        f&quot;user:{instance.id}:state&quot;,<br>    ])<br><br><br>@receiver(post_save, sender=Interest)<br>def invalidate_trending_cache(sender, **kwargs):<br>    cache.delete_pattern(&quot;trending:interests:*&quot;)  # django-redis only</pre><h3>4. Calibrate TTLs to Data Sensitivity</h3><p>Monitoring Redis from Django</p><pre># views/health.py<br>from django_redis import get_redis_connection<br>from rest_framework.views import APIView<br>from rest_framework.response import Response<br><br><br>class RedisHealthView(APIView):<br>    permission_classes = []<br><br>    def get(self, request):<br>        redis_client = get_redis_connection(&quot;default&quot;)<br><br>        stats = redis_client.info(&quot;stats&quot;)<br>        hits = stats.get(&quot;keyspace_hits&quot;, 0)<br>        misses = stats.get(&quot;keyspace_misses&quot;, 0)<br>        total = hits + misses<br>        hit_rate = round((hits / total) * 100, 1) if total &gt; 0 else 0<br><br>        memory = redis_client.info(&quot;memory&quot;)<br><br>        return Response({<br>            &quot;status&quot;: &quot;healthy&quot; if hit_rate &gt; 80 else &quot;warning&quot;,<br>            &quot;hit_rate&quot;: f&quot;{hit_rate}%&quot;,<br>            &quot;memory_used&quot;: memory.get(&quot;used_memory_human&quot;),<br>            &quot;connected_clients&quot;: redis_client.info(&quot;clients&quot;).get(&quot;connected_clients&quot;),<br>        })</pre><p>A healthy cache hit rate is <strong>above 90%</strong>. Below 80%, your TTLs are probably too short or your cache keys too specific.</p><h3>What Redis Changed on Seendr — Real Numbers</h3><ul><li>Average matching time: 800ms → **68ms**<br>- Max simultaneous connections: ~400 → **5,000+**<br>- PostgreSQL queries/min: 12,000 → **1,100**<br>- Cache hit rate: 0% → **94%**<br>- Monthly infrastructure cost: €85 → **€42**</li></ul><p>This is not just about speed. It is a 50% reduction in infrastructure costs, because the database is under far less pressure.</p><h3>Where to Start This Week</h3><p><strong>Day 1</strong> — Add django-redis and configure CACHES. Decorate your most-called view with @cache_page. Measure before and after with Django Debug Toolbar.</p><p><strong>Day 2</strong> — Migrate your sessions to Redis (SESSION_ENGINE = &quot;django.contrib.sessions.backends.cache&quot;).</p><p><strong>Week 1</strong> — Add rate limiting to your sensitive endpoints. Configure the Channel Layer for Django Channels.</p><p><strong>Week 2</strong> — Move slow tasks (email sending, image processing) to Celery with Redis as the broker.</p><p>The best Redis implementations I have seen all evolved incrementally. Start small. Measure. Iterate.</p><h3>FAQ</h3><p><strong>django-redis or Django&#39;s native Redis backend?</strong> django-redis in 2026. It exposes the raw Redis client via get_redis_connection(), supports delete_pattern(), and provides far more configuration options. The native backend is too limited for anything beyond basic caching.</p><p><strong>Can Redis replace PostgreSQL?</strong> No. Redis is for data that is acceptable to lose, or data that requires microsecond access. For transactions and data integrity, PostgreSQL remains non-negotiable. On Seendr, both coexist.</p><p><strong>How much does Redis cost in production?</strong> Between €0 (Redis Cloud free tier, 30MB) and €15/month (AWS ElastiCache, minimum instance). For variable traffic, Upstash pay-per-request is often the most economical starting point.</p><p><strong>Do I need Redis if I already use Django Channels?</strong> Yes — it is mandatory. Django Channels requires a channel layer to function correctly across multiple instances in production. Redis is the reference backend.</p><p><strong>My hit rate is at 65%. What should I do?</strong> Increase your TTLs if your data changes infrequently. Make sure your cache keys are not too specific. Use Django Debug Toolbar to identify the views with the most cache misses and prioritize them.</p><p><em>Diderot Sielinou — Full-stack Python/Django developer, creator of Seendr.</em> <em>If this article helped you, share it with a developer building a real-time Django application.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=770f1e51721d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD en 2026 : La compétence qui sépare les développeurs JavaScript junior des senior]]></title>
            <link>https://medium.com/@diderotsielinou/ci-cd-en-2026-la-comp%C3%A9tence-qui-s%C3%A9pare-les-d%C3%A9veloppeurs-javascript-junior-des-senior-3fab9b46da9a?source=rss-8b07c70272d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fab9b46da9a</guid>
            <dc:creator><![CDATA[Diderot Sielinou]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 06:12:48 GMT</pubDate>
            <atom:updated>2026-03-05T06:12:48.554Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEr0T1eDTAcobDCemZSxpQ.png" /></figure><p>67 % des offres d’emploi senior JavaScript exigent maintenant des compétences CI/CD. Pas “un plus”. Une <strong>exigence</strong>. Il y a deux ans, ce chiffre était à 40 %.</p><p>Les équipes rétrécissent. Les budgets DevOps disparaissent. Aujourd’hui, on attend du développeur JavaScript senior qu’il écrive le code, configure le pipeline, déploie en production et surveille ce qui se passe après. Tout ça. Seul.</p><p>Si vous avez traité le CI/CD comme “le problème de quelqu’un d’autre”, 2026 est l’année où ça change.</p><h3>Pourquoi le CI/CD est devenu incontournable</h3><p>L’économie a changé. En 2023, une startup avait 8 développeurs et un DevOps dédié. En 2026, elle a 4 développeurs et zéro DevOps. L’infrastructure est gérée par des services cloud. Les pipelines sont des fichiers YAML dans le repo. La responsabilité appartient à tout le monde.</p><p>L’IA a accéléré cette évolution. Un assistant IA génère un composant React en 30 secondes. Le vrai goulot d’étranglement n’est plus d’écrire du code — c’est de le livrer sans tout casser.</p><p>Les salaires le confirment : les développeurs JavaScript avec des compétences CI/CD gagnent <strong>15 à 25 % de plus</strong> que les autres. Cet écart se creuse, parce que peu de développeurs comprennent les pipelines assez bien pour les concevoir et les déboguer.</p><h3>CI vs CD : la différence que beaucoup confondent</h3><p><strong>CI (Intégration Continue)</strong> : chaque push déclenche automatiquement des tests, une vérification des types, un lint, et un build. Le but : détecter les problèmes en minutes, pas en jours.</p><p><strong>CD (Déploiement Continu)</strong> : le code validé par la CI est livré automatiquement aux utilisateurs.</p><p>Vous pouvez avoir la CI sans le CD. Beaucoup d’équipes font tourner la CI sur chaque PR mais déploient manuellement une fois par semaine. C’est déjà bien. Mais les seniors font les deux.</p><h3>Configurer GitHub Actions pour un projet JavaScript</h3><p>GitHub Actions est la plateforme CI/CD dominante en 2026. Plus de 80 % des projets JavaScript open source l’utilisent. La config se trouve dans .github/workflows/ sous forme de fichiers YAML.</p><p>Voici un pipeline CI réaliste pour une app Next.js avec TypeScript :</p><pre><br>name: CI<br><br>on:<br>  push:<br>    branches: [main]<br>  pull_request:<br>    branches: [main]<br><br>concurrency:<br>  group: ci-${{ github.ref }}<br>  cancel-in-progress: true<br><br>jobs:<br>  validate:<br>    runs-on: ubuntu-latest<br>    strategy:<br>      matrix:<br>        node-version: [20, 22]<br><br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - name: Setup Node.js<br>        uses: actions/setup-node@v4<br>        with:<br>          node-version: ${{ matrix.node-version }}<br>          cache: &#39;npm&#39;<br><br>      - name: Install dependencies<br>        run: npm ci<br><br>      - name: Lint<br>        run: npm run lint<br><br>      - name: Type check<br>        run: npx tsc --noEmit<br><br>      - name: Unit tests<br>        run: npm test -- --coverage<br><br>      - name: Build<br>        run: npm run build</pre><p>Trois points importants :</p><ul><li>Le bloc concurrency annule les runs en cours quand vous poussez un nouveau commit sur la même branche. Sans ça, trois corrections rapides = trois pipelines en parallèle.</li><li>npm ci ≠ npm install. Il installe les versions exactes du lockfile. Les builds sont reproductibles.</li><li>La matrix teste sur Node 20 et 22, ce qui détecte les problèmes de compatibilité tôt.</li></ul><h3>Réduire le temps de pipeline avec le cache</h3><p>Installer des dépendances peut prendre 45 à 90 secondes pour un projet moyen. Le cache élimine ce problème.</p><pre>- name: Cache node_modules<br>  id: cache-deps<br>  uses: actions/cache@v4<br>  with:<br>    path: node_modules<br>    key: deps-${{ runner.os }}-${{ hashFiles(&#39;package-lock.json&#39;) }}<br><br>- name: Install dependencies<br>  if: steps.cache-deps.outputs.cache-hit != &#39;true&#39;<br>  run: npm ci</pre><p>Si le lockfile n’a pas changé, npm ci est complètement ignoré. Sur un projet typique, ça économise 60 à 90 secondes par run. Multipliez par 50 PRs par semaine : vous gagnez des heures.</p><p>Pour les monorepos avec Turborepo, le cache distant est encore plus puissant. il peut permettre a des pipelines passer de 12 minutes à 3 minutes avec un cache distant bien configuré.</p><h3>De la CI à la production : comment le code rejoint vraiment les utilisateurs</h3><p>Le pipeline de déploiement le plus simple ressemble à ça : le code fusionne dans main, la CI tourne, si tout est vert → déploiement en staging, tests smoke, si vert → déploiement en production.</p><h3>Déployer une app Next.js avec Vercel</h3><pre>name: Deploy<br><br>on:<br>  push:<br>    branches: [main]<br><br>jobs:<br>  deploy-staging:<br>    runs-on: ubuntu-latest<br>    environment: staging<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: actions/setup-node@v4<br>        with:<br>          node-version: 22<br>          cache: &#39;npm&#39;<br>      - run: npm ci<br>      - run: npm test<br>      - run: npm run build<br>      - name: Deploy to staging<br>        run: npx vercel --prod --token=${{ secrets.VERCEL_TOKEN }}<br>        env:<br>          VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}<br>          VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}<br><br>  deploy-production:<br>    needs: deploy-staging<br>    runs-on: ubuntu-latest<br>    environment:<br>      name: production<br>      url: https://yourapp.com<br>    steps:<br>      - name: Deploy to production<br>        run: npx vercel --prod --token=${{ secrets.VERCEL_TOKEN }}<br>        env:<br>          VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}<br>          VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}</pre><p>Le mot-clé environment est crucial. Il permet de mettre en place une approbation manuelle avant le déploiement en production. Le staging se déploie automatiquement. La production attend qu&#39;un humain clique &quot;Approuver&quot;. Pour une petite équipe, c&#39;est le bon équilibre entre vitesse et sécurité.</p><h3>Docker pour les services Node.js backend</h3><p>Pas tout le monde déploie sur Vercel. Les APIs et microservices partent en containers Docker vers AWS ECS, Google Cloud Run, ou Kubernetes. Comprendre Docker est maintenant une compétence de base pour un développeur JavaScript senior.</p><pre>FROM node:22-alpine AS builder<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm ci --only=production<br>COPY . .<br>RUN npm run build<br><br>FROM node:22-alpine AS runner<br>WORKDIR /app<br>RUN addgroup -g 1001 -S nodejs &amp;&amp; adduser -S nextjs -u 1001<br>COPY --from=builder --chown=nextjs:nodejs /app/dist ./dist<br>COPY --from=builder --chown=nextjs:nodejs /app/node_modules ./node_modules<br>COPY --from=builder --chown=nextjs:nodejs /app/package.json ./<br>USER nextjs<br>EXPOSE 3000<br>ENV NODE_ENV=production<br>CMD [&quot;node&quot;, &quot;dist/server.js&quot;]</pre><p>Le build multi-stage n’est pas optionnel. Le stage builder a toutes les devDependencies. Le stage runner n&#39;a que les dépendances de production et le code compilé. L&#39;image passe de 800 Mo+ à moins de 200 Mo.</p><pre>- name: Build and push Docker image<br>  uses: docker/build-push-action@v5<br>  with:<br>    context: .<br>    push: true<br>    tags: |<br>      your-registry.com/api:${{ github.sha }}<br>      your-registry.com/api:latest<br>    cache-from: type=gha<br>    cache-to: type=gha,mode=max</pre><p>Le tag avec github.sha crée un lien direct entre chaque commit et son image déployée. Quand la production plante à 3h du matin, vous savez exactement quel commit tourne.</p><h3>Tests dans le pipeline CI : l’ordre compte</h3><p>Les tests locaux et les tests en CI ne sont pas la même chose. Localement, votre base de données tourne, vos variables d’environnement sont configurées. En CI, c’est un serveur vierge. C’est là que les développeurs perdent des heures.</p><p>L’ordre optimal :</p><pre>steps:<br>  - name: Lint et vérification des types<br>    run: |<br>      npm run lint<br>      npx tsc --noEmit<br><br>  - name: Tests unitaires<br>    run: npm test -- --coverage --bail<br><br>  - name: Tests d&#39;intégration<br>    run: npm run test:integration<br><br>  - name: Tests E2E<br>    run: npx playwright test</pre><p>Lint et types en premier : le plus rapide, attrape les erreurs évidentes. Si vous avez une erreur TypeScript, inutile de lancer 500 tests unitaires. Le flag --bail arrête à la première erreur plutôt que d&#39;afficher 47 échecs. Les tests E2E en dernier : les plus lents, les plus coûteux.</p><h3>Tests avec base de données en CI</h3><pre>jobs:<br>  integration-tests:<br>    runs-on: ubuntu-latest<br>    services:<br>      postgres:<br>        image: postgres:16<br>        env:<br>          POSTGRES_USER: test<br>          POSTGRES_PASSWORD: test<br>          POSTGRES_DB: testdb<br>        ports:<br>          - 5432:5432<br>        options: &gt;-<br>          --health-cmd pg_isready<br>          --health-interval 10s<br>          --health-timeout 5s<br>          --health-retries 5<br>      redis:<br>        image: redis:7<br>        ports:<br>          - 6379:6379<br>    steps:<br>      - uses: actions/checkout@v4<br>      - name: Run integration tests<br>        run: npm run test:integration<br>        env:<br>          DATABASE_URL: postgresql://test:test@localhost:5432/testdb<br>          REDIS_URL: redis://localhost:6379</pre><p>L’option --health-cmd est facile à oublier et essentielle. Sans elle, vos tests démarrent avant que PostgreSQL soit prêt, ce qui cause des échecs aléatoires.</p><h3>Variables d’environnement et secrets</h3><p>Stocker des secrets dans GitHub Secrets et les référencer dans les workflows est le minimum. Voici le pattern de base :</p><pre>jobs:<br>  deploy-staging:<br>    environment: staging<br>    steps:<br>      - name: Deploy<br>        env:<br>          DATABASE_URL: ${{ secrets.DATABASE_URL }}<br>          API_URL: https://api-staging.yourapp.com<br><br>  deploy-production:<br>    environment: production<br>    steps:<br>      - name: Deploy<br>        env:<br>          DATABASE_URL: ${{ secrets.DATABASE_URL }}<br>          API_URL: https://api.yourapp.com</pre><p>Chaque environnement a ses propres secrets. Le DATABASE_URL de staging pointe vers la base de staging. Celui de production vers la base de production. Même nom, valeur différente. Ça évite l&#39;erreur classique : du code de staging qui tourne contre la base de production.</p><h3>Le piège des variables côté client</h3><p>Les variables comme NEXT_PUBLIC_API_URL sont intégrées dans le bundle JavaScript <strong>au moment du build</strong>, pas à l&#39;exécution. Résultat : vous ne pouvez pas promouvoir le même build de staging à production.</p><p>La solution : la configuration au runtime.</p><pre>export async function getConfig() {<br>  if (typeof window !== &#39;undefined&#39;) {<br>    const response = await fetch(&#39;/api/config&#39;);<br>    return response.json();<br>  }<br>  return {<br>    apiUrl: process.env.API_URL,<br>    analyticsId: process.env.ANALYTICS_ID,<br>  };<br>}</pre><p>Ou plus simplement, via un tag &lt;script&gt; rendu côté serveur</p><pre>&lt;script&gt;<br>  window.__CONFIG__ = {<br>    apiUrl: &quot;{{API_URL}}&quot;,<br>    analyticsId: &quot;{{ANALYTICS_ID}}&quot;<br>  };<br>&lt;/script&gt;</pre><p>Le serveur remplace les placeholders à l’exécution. Un seul build fonctionne dans tous les environnements. C’est le pattern que les seniors comprennent et que les juniors n’implémentent presque jamais.</p><h3>Stratégies de déploiement : zéro downtime</h3><h3>Blue-Green : deux environnements, un switch</h3><p>Deux environnements de production identiques. Blue = la version live actuelle. Green = là où vous déployez la nouvelle version. Une fois Green validé, vous basculez le trafic. Si ça plante, vous rebasculez sur Blue en une commande.</p><pre>- name: Deploy to green<br>  run: |<br>    aws ecs update-service \<br>      --cluster production \<br>      --service api-green \<br>      --task-definition api:${{ steps.task-def.outputs.revision }}<br><br>- name: Attendre la stabilisation<br>  run: |<br>    aws ecs wait services-stable \<br>      --cluster production \<br>      --services api-green<br><br>- name: Smoke tests sur green<br>  run: |<br>    curl -f https://green.api.yourapp.com/health || exit 1<br>    npm run test:smoke -- --base-url=https://green.api.yourapp.com<br><br>- name: Basculer le trafic vers green<br>  run: |<br>    aws elbv2 modify-listener \<br>      --listener-arn ${{ secrets.ALB_LISTENER_ARN }} \<br>      --default-actions Type=forward,TargetGroupArn=${{ secrets.GREEN_TG_ARN }}</pre><p>Si le smoke test échoue, le pipeline s’arrête. Les utilisateurs ne voient jamais le code cassé.</p><h3>Canary : 10 % du trafic d’abord</h3><p>Envoyez 10 % du trafic vers la nouvelle version. Si les erreurs restent normales, passez à 100 %. Si elles explosent, revenez à 0 %. Indispensable pour les bugs qui n’apparaissent que sous vrai trafic (Safari mobile, cas limites réels, etc.).</p><pre>- name: Déployer canary (10% du trafic)<br>  run: |<br>    aws elbv2 modify-rule \<br>      --rule-arn ${{ secrets.CANARY_RULE_ARN }} \<br>      --actions &#39;[{&quot;Type&quot;: &quot;forward&quot;, &quot;ForwardConfig&quot;: {<br>        &quot;TargetGroups&quot;: [<br>          {&quot;TargetGroupArn&quot;: &quot;${{ secrets.STABLE_TG }}&quot;, &quot;Weight&quot;: 90},<br>          {&quot;TargetGroupArn&quot;: &quot;${{ secrets.CANARY_TG }}&quot;, &quot;Weight&quot;: 10}<br>        ]<br>      }}]&#39;<br><br>- name: Surveiller les erreurs pendant 10 minutes<br>  run: node scripts/monitor-canary.js --duration=600 --threshold=0.5<br><br>- name: Promouvoir à 100%<br>  if: success()<br>  run: |<br>    aws elbv2 modify-rule \<br>      --rule-arn ${{ secrets.CANARY_RULE_ARN }} \<br>      --actions &#39;[{&quot;Type&quot;: &quot;forward&quot;, &quot;ForwardConfig&quot;: {<br>        &quot;TargetGroups&quot;: [<br>          {&quot;TargetGroupArn&quot;: &quot;${{ secrets.CANARY_TG }}&quot;, &quot;Weight&quot;: 100}<br>        ]<br>      }}]&#39;</pre><p>Si une métrique dépasse le seuil, le pipeline rollback automatiquement. Personne ne se réveille à 3h.</p><h3>Vérification post-déploiement et rollback automatique</h3><p>Un déploiement réussi ne veut pas dire que ça marche pour les vrais utilisateurs. J’ai vu des déploiements passer tous les tests et quand même casser le tunnel de paiement pour 20 % des utilisateurs, à cause d’une race condition invisible en CI.</p><pre>const checks = [<br>  { name: &#39;API Health&#39;, url: &#39;/api/health&#39;, expected: 200 },<br>  { name: &#39;Database&#39;, url: &#39;/api/health/db&#39;, expected: 200 },<br>  { name: &#39;Redis&#39;, url: &#39;/api/health/redis&#39;, expected: 200 },<br>  { name: &#39;Homepage&#39;, url: &#39;/&#39;, expected: 200, contains: &#39;&lt;div id=&quot;app&quot;&gt;&#39; },<br>];<br><br>async function runChecks(baseUrl, retries = 3) {<br>  for (const check of checks) {<br>    let lastError;<br>    for (let attempt = 0; attempt &lt; retries; attempt++) {<br>      try {<br>        const response = await fetch(`${baseUrl}${check.url}`);<br>        if (response.status !== check.expected)<br>          throw new Error(`${check.name}: attendu ${check.expected}, reçu ${response.status}`);<br>        if (check.contains) {<br>          const body = await response.text();<br>          if (!body.includes(check.contains))<br>            throw new Error(`${check.name}: contenu attendu absent`);<br>        }<br>        console.log(`PASS: ${check.name}`);<br>        lastError = null;<br>        break;<br>      } catch (error) {<br>        lastError = error;<br>        await new Promise(r =&gt; setTimeout(r, 2000));<br>      }<br>    }<br>    if (lastError) { console.error(`FAIL: ${lastError.message}`); process.exit(1); }<br>  }<br>}<br><br>runChecks(process.env.DEPLOY_URL);</pre><pre>- name: Vérification post-déploiement<br>  id: verify<br>  continue-on-error: true<br>  run: node scripts/post-deploy-check.js<br>  env:<br>    DEPLOY_URL: https://yourapp.com<br><br>- name: Rollback si échec<br>  if: steps.verify.outcome == &#39;failure&#39;<br>  run: |<br>    aws ecs update-service \<br>      --cluster production \<br>      --service api \<br>      --task-definition api:${{ steps.previous-version.outputs.revision }}</pre><p>Les développeurs sont notifiés, mais les utilisateurs ne voient jamais la version cassée plus de quelques minutes.</p><h3>Sécurité du pipeline CI/CD</h3><p>Votre pipeline a plus d’accès qu’un humain : credentials de base de données, clés cloud, tokens de déploiement. Un pipeline compromis = une application compromise.</p><h3>Attaques via les dépendances npm</h3><p>La menace principale en 2026 n’est pas un hack direct. C’est un package npm compromis. Une librairie populaire est détournée, publie une version malveillante, et votre CI l’installe automatiquement au prochain build.</p><p>Verrouillez vos actions sur des SHA exacts, pas des tags :</p><pre># MAUVAIS — le tag peut pointer vers du code malveillant<br>- uses: actions/checkout@v4<br><br># BON — le SHA est immuable<br>- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11</pre><p>Ajoutez un audit de sécurité dans votre pipeline :</p><pre>- name: Security audit<br>  run: npm audit --audit-level=critical</pre><h3>OIDC plutôt que des secrets long-lived</h3><p>Au lieu de stocker AWS_ACCESS_KEY_ID comme secret, utilisez OpenID Connect pour demander des tokens temporaires directement au cloud provider :</p><pre>permissions:<br>  id-token: write<br>  contents: read<br><br>steps:<br>  - name: Configure AWS credentials<br>    uses: aws-actions/configure-aws-credentials@v4<br>    with:<br>      role-to-assume: arn:aws:iam::123456789:role/github-deploy<br>      aws-region: us-east-1</pre><p>Aucune clé stockée nulle part. Le token est généré pour chaque run et expire en quelques minutes.</p><h3>Ce que les interviewers attendent des candidats senior en 2026</h3><p>CI/CD apparaît dans presque chaque cycle d’entretien senior JavaScript — pas comme un round DevOps séparé, mais intégré dans les questions de system design.</p><p>Les trois questions les plus courantes :</p><ol><li><strong>“Expliquez comment le code passe de votre machine locale à la production.”</strong> → Teste si vous comprenez l’ensemble du pipeline ou si vous faites juste git push et espérez.</li><li><strong>“Un déploiement casse la production à 2h du matin. Que se passe-t-il ?”</strong> → Teste votre stratégie de rollback et de monitoring.</li><li><strong>“Comment gérez-vous la configuration entre dev, staging et production ?”</strong> → Teste si vous comprenez le problème build-time vs runtime.</li></ol><p>Deux candidats peuvent concevoir la même architecture. Celui qui explique comment la déployer, la tester en staging, la canary à 10 % des utilisateurs et surveiller les taux d’erreur — celui-là aura toujours un meilleur score.</p><h3>Les erreurs typiques des développeurs mid-level</h3><p>La plus grosse erreur : décrire CI/CD comme un processus linéaire. Push → tests → déploiement. Les seniors comprennent que c’est une <strong>boucle de feedback</strong>. Les métriques de production alimentent le pipeline. Les tests flaky sont mis en quarantaine automatiquement. La fréquence de déploiement informe la planification des sprints.</p><p>Autre erreur : dire “notre équipe DevOps s’occupe du pipeline” dans un entretien senior. En 2026, le pipeline est votre code. Vous devez pouvoir l’écrire, le déboguer et l’améliorer.</p><h3>Quelle plateforme CI/CD choisir ?</h3><p><strong>GitHub Actions</strong> domine l’écosystème JavaScript. +80 % des projets open source l’utilisent. Intégration native avec GitHub, marketplace riche, tier gratuit généreux. C’est le choix par défaut.</p><p><strong>GitLab CI</strong> est le deuxième choix, surtout pour les équipes déjà sur GitLab. Sa syntaxe de pipeline est plus puissante pour les workflows complexes.</p><p><strong>Jenkins</strong> est encore présent dans de grandes entreprises mais c’est rarement le bon choix pour un nouveau projet en 2026. Coût de maintenance élevé, écosystème de plugins fragile.</p><p><strong>CircleCI et Travis CI</strong> ont perdu une grande part de marché au profit de GitHub Actions.</p><p>Ma recommandation : apprenez GitHub Actions en profondeur. Si votre entreprise utilise autre chose, les concepts se transfèrent directement — c’est juste une syntaxe différente.</p><h3>Monorepos : ils cassent différemment</h3><p>Les monorepos (un repo avec frontend Next.js, API Node.js, librairie partagée, etc.) deviennent courants. Turborepo et Nx dominent en 2026. Mais ils introduisent un problème nouveau : <strong>le build sélectif</strong>.</p><p>Quand quelqu’un modifie seulement un handler d’API, reconstruire et redéployer le frontend est une perte de temps et un risque inutile.</p><pre>jobs:<br>  detect-changes:<br>    runs-on: ubuntu-latest<br>    outputs:<br>      frontend: ${{ steps.filter.outputs.frontend }}<br>      api: ${{ steps.filter.outputs.api }}<br>    steps:<br>      - uses: actions/checkout@v4<br>      - uses: dorny/paths-filter@v3<br>        id: filter<br>        with:<br>          filters: |<br>            frontend:<br>              - &#39;apps/frontend/**&#39;<br>              - &#39;packages/shared/**&#39;<br>            api:<br>              - &#39;apps/api/**&#39;<br>              - &#39;packages/shared/**&#39;<br><br>  deploy-frontend:<br>    needs: detect-changes<br>    if: needs.detect-changes.outputs.frontend == &#39;true&#39;<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - run: npx turbo run build --filter=frontend<br>      - run: npx turbo run deploy --filter=frontend<br><br>  deploy-api:<br>    needs: detect-changes<br>    if: needs.detect-changes.outputs.api == &#39;true&#39;<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v4<br>      - run: npx turbo run build --filter=api<br>      - run: npx turbo run deploy --filter=api</pre><p>Un changement dans packages/shared/ déclenche les deux déploiements (les deux en dépendent). Un changement dans apps/api/ déclenche uniquement le déploiement de l&#39;API.</p><p>Sans ça, chaque commit reconstruit et redéploie tout. Dans un monorepo avec 5 apps, une correction d’une ligne dans un README = 5 déploiements. C’est lent et 5x plus risqué.</p><h3>Commencez cette semaine, pas le mois prochain</h3><p>Si vous n’avez pas encore de pipeline CI/CD sur votre projet, voici quoi faire <strong>cette semaine</strong>.</p><p>Créez .github/workflows/ci.yml avec trois étapes : installer les dépendances, lancer le lint, lancer les tests. C&#39;est tout. Poussez. Regardez tourner. Corrigez ce qui casse. Ça prend 20 minutes.</p><p>Ensuite ajoutez la vérification des types TypeScript. Puis le build. Puis le cache. Puis le déploiement en staging. Chaque ajout prend 15 à 30 minutes et rend votre projet plus professionnel.</p><p>Les meilleures pipelines que j’ai vues ont toutes évolué de façon itérative. Elles ont commencé avec lint + tests. Elles ont ajouté le déploiement après un incident en production. Elles ont ajouté le canary après une mauvaise release qui a touché tous les utilisateurs d’un coup.</p><p>Dans un an, vous serez soit le développeur qui possède le pipeline, soit celui qui attend que quelqu’un d’autre déploie son code. En 2026, avec des équipes qui rétrécissent et des attentes qui grandissent, le deuxième profil n’a plus sa place.</p><p>Le code qui n’atteint jamais les utilisateurs n’existe pas vraiment. Le CI/CD, c’est ce qui rend votre travail réel.</p><h3>FAQ</h3><p><strong>Dois-je apprendre le CI/CD si je suis développeur frontend ?</strong> Oui. La frontière frontend/full-stack s’efface. Les interviewers posent des questions sur les stratégies de déploiement, la configuration d’environnement et le monitoring aux candidats frontend.</p><p><strong>Combien de temps faut-il pour mettre en place un pipeline de base ?</strong> Un pipeline avec lint, types et tests : 20 à 30 minutes. Ajouter le déploiement en staging : une heure de plus. Un pipeline complet avec canary et rollback automatique : des jours à des semaines, mais vous ne construisez pas tout ça d’un coup.</p><p><strong>GitHub Actions ou GitLab CI ?</strong> Utilisez ce sur quoi votre repo est hébergé. Les concepts sont identiques, la syntaxe diffère légèrement. Changer de plateforme prend une journée, pas une semaine.</p><p><strong>Quelle est la vraie différence entre CI et CD ?</strong> La CI intègre le code fréquemment avec des tests automatisés. La CD livre ce code validé aux utilisateurs. Vous pouvez avoir la CI sans le CD. Commencez par la CI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fab9b46da9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My First Command Line Tool with Node.js and PostgreSQL — A CLI Contact Book]]></title>
            <link>https://medium.com/@diderotsielinou/my-first-command-line-tool-with-node-js-and-postgresql-a-cli-contact-book-6013c82b69f7?source=rss-8b07c70272d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/6013c82b69f7</guid>
            <dc:creator><![CDATA[Diderot Sielinou]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 13:24:42 GMT</pubDate>
            <atom:updated>2025-04-25T13:24:42.803Z</atom:updated>
            <content:encoded><![CDATA[<h3>My First Command Line Tool with Node.js and PostgreSQL — A CLI Contact Book</h3><p>“Building a Tool I’d Actually Use, From Scratch with Node.js”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*I1o3OXHqyVTpDD1AHDybng.png" /></figure><p>After two weeks of learning Node.js at Rebase Code Camp, I was tasked with creating a practical command-line tool (CLI) to manage personal contacts directly from the terminal.”<strong> This project allowed me to implement key concepts such as:</strong></p><ul><li>Creating Command-Line Applications with Node.js</li><li>All CRUD operations — creating, reading, updating and deleting contacts — plus search functionality</li><li>Using PostgreSQL as the database system</li><li>Code organization, error handling, and best practices including server-side data validation before database persistence</li></ul><p>In this post, I’ll break down how the tool functions, demonstrate simple commands to use it, and share the libraries that made it possible. First, though — what exactly is a CLI tool, and why should you care?</p><h3><strong>Advantages of Using a CLI Tool</strong></h3><p>CLI tools offer significant benefits, including:</p><ol><li><strong>Execution Speed</strong> — Run commands with a single line, faster than navigating graphical interfaces.</li><li><strong>Easy Automation</strong> — Ideal for scripting, CI/CD pipelines, and DevOps workflows.</li><li><strong>Lightweight</strong> — No GUI overhead, resulting in smaller footprint and better performance.</li><li><strong>Developer-Friendly</strong> — Preferred by engineers for technical tasks due to greater power and efficiency.</li></ol><h3>Technologies Used</h3><p>The project leverages these core libraries:</p><ol><li><strong>commander</strong> — For building CLI commands with ease</li><li><strong>pg</strong> (node-postgres) — PostgreSQL client for Node.js</li><li><strong>chalk</strong> — Terminal output styling with colors</li></ol><h3>How the Tool Works</h3><p>The CLI tool runs using node contacts.js followed by subcommands.</p><p><strong>Usage Examples:</strong></p><pre> contacts add --name &quot;Alice&quot; --email &quot;alice@example.com&quot; --phone &quot;+237 652643426&quot;</pre><pre>contacts list</pre><pre>contacts update --id 2 --phone &quot;987654321&quot;</pre><pre>contacts delete --id 3</pre><pre>contacts search --keyword &quot;diderot&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*BlW8FUp-yO4uJpq_UrE1Ag.png" /><figcaption>example of using the <strong>list</strong> command</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*IFT6EuOzZq-NrSCCtFu4Ag.png" /><figcaption>example of using the <strong>add</strong> command</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*n4t2tiNR-FEXTA9MOo6UUA.png" /><figcaption>example of using the <strong>search</strong> command</figcaption></figure><h3>Built-in Help Documentation</h3><p>One of <strong>commander.js</strong>’s key strengths is its auto-generated command-line help.<br>Simply run:</p><pre> contacts --help</pre><p>And you will see something like:</p><pre>Usage: contacts [options] [command]<br><br>Options:<br>  -h, --help        display help for command<br><br>Commands:<br>  add               Ajouter un nouveau contact<br>  list              Lister tous les contacts<br>  search            Rechercher un contact par nom<br>  update            Mettre à jour un contact<br>  delete            Supprimer un contact<br>  help [command]    display help for command</pre><p>Each command also has its own help:</p><pre> contacts add --help</pre><h3><strong>Challenges Encountered</strong></h3><p>Like any serious project, it wasn’t without its struggles. I faced several difficulties, such as:</p><ul><li><strong>Database errors</strong> (Incorrect column types, silently failing queries, encoding issues with special characters).</li><li><strong>CLI logic</strong> (Commander is very powerful, but understanding how subcommands, required and optional options work wasn’t immediately intuitive).</li><li><strong>Asynchronous operations with PostgreSQL</strong> (Managing asynchronous queries while keeping the code readable forced me to fully grasp async/await).</li><li><strong>User input validation</strong> (I had to spend time learning regular expressions in JavaScript, which allowed me to define a data schema for each field).</li></ul><p>My mentors helped me a lot in structuring the database properly, and my classmates provided great support. Thanks to their guidance and extensive research, I was able to overcome these challenges.</p><h3>Conclusion</h3><p>This project allowed me to gain valuable skills, such as:</p><ul><li>Building a professional CLI tool using <strong>Commander</strong></li><li>Managing a <strong>PostgreSQL</strong> database with <strong>Node.js</strong></li><li>Writing <strong>clean, modular, and maintainable</strong> code</li><li>Securing sensitive data with <strong>environment variables</strong></li><li>Debugging <strong>database errors</strong> effectively</li><li>Validating user input using <strong>regular expressions</strong></li></ul><p>This project was a <strong>real leap forward</strong> in my skills. It taught me how to build a tool I now use daily, tackling real technical challenges — <strong>databases, CLI design, architecture, security, and best practices</strong>.</p><p>If you also want to learn how to build a <strong>Node.js CLI tool</strong>, start small… but <strong>think like a pro</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6013c82b69f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mon Parcours Passionnant avec React JS : Défis, Réussites et Apprentissages]]></title>
            <link>https://medium.com/@diderotsielinou/mon-parcours-passionnant-avec-react-js-d%C3%A9fis-r%C3%A9ussites-et-apprentissages-01c179fd5e27?source=rss-8b07c70272d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/01c179fd5e27</guid>
            <dc:creator><![CDATA[Diderot Sielinou]]></dc:creator>
            <pubDate>Thu, 20 Mar 2025 10:31:58 GMT</pubDate>
            <atom:updated>2025-03-20T10:31:58.819Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mon Parcours Passionnant avec React JS : Défis, Réussites et Apprentissages</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*eTvPmdLIUX9B7WOtnjOMfA.jpeg" /></figure><p>React est une bibliothèque JavaScript déclarative, efficace et flexible pour construire des interfaces utilisateur. Son approche unique et son écosystème riche en ont fait le choix privilégié de nombreux développeurs pour créer des applications web complexes et performantes, aussi bien des applications monopages (SPA) que des applications plus traditionnelles. Plutôt qu’une simple bibliothèque, React est devenu un véritable écosystème, avec des outils et des librairies complémentaires qui facilitent le développement d’applications de grande envergure.</p><p>Mon aventure avec React JS chez RebaseCodeCamp a été bien plus qu’une simple formation technique : c’était une véritable expérience humaine et professionnelle. Dans cet article, je partage mes défis personnels, mes succès, et l’environnement stimulant qui m’a permis de découvrir ce framework puissant, tout en mettant en lumière l’accompagnement exceptionnel de mon tuteur et l’esprit collaboratif de mes camarades.</p><h3>Les Défis de l’Apprentissage de React JS</h3><p>Dès mes premiers pas dans React, j’ai été confronté à une courbe d’apprentissage abrupte. Comprendre le fonctionnement des <strong>composants fonctionnels</strong>, l’utilisation des <strong>hooks</strong> (notamment useState et useEffect), et l&#39;architecture déclarative de React était un véritable défi. Je me souviens encore de mes premières tentatives pour gérer l&#39;état d&#39;une application complexe : la logique se mélangeait, et les bugs apparaissaient sans raison apparente. Ces moments de frustration étaient difficiles, mais ils m&#39;ont poussé à approfondir mes connaissances et à expérimenter avec persévérance.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function DataFetcher() {<br>  const [data, setData] = useState(null);<br>  const [error, setError] = useState(null);<br>  const [loading, setLoading] = useState(true);<br><br>  useEffect(() =&gt; {<br>    const fetchData = async () =&gt; {<br>      try {<br>        const response = await fetch(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;); // Remplacez par votre API<br>        if (!response.ok) {<br>          throw new Error(`HTTP error! status: ${response.status}`);<br>        }<br>        const jsonData = await response.json();<br>        setData(jsonData);<br>      } catch (error) {<br>        setError(error);<br>      } finally {<br>        setLoading(false);<br>      }<br>    };<br><br>    fetchData();<br>  }, []); // Le tableau vide [] assure que l&#39;effet ne s&#39;exécute qu&#39;une seule fois après le montage.<br><br>  if (loading) return &lt;p&gt;Chargement...&lt;/p&gt;;<br>  if (error) return &lt;p&gt;Erreur: {error.message}&lt;/p&gt;;<br>  if (!data) return null;<br><br>  return (<br>    &lt;pre&gt;{JSON.stringify(data, null, 2)}&lt;/pre&gt;<br>  );<br>}<br><br>export default DataFetcher;</pre><p>Ici, `useEffect` effectue une requête fetch à une API et met à jour l’état `data` avec les données récupérées. Le `[]` vide comme deuxième argument indique que l’effet ne s’exécute qu’une seule fois après le montage du composant. Gestion d’erreur et chargement sont inclus pour une meilleure expérience utilisateur.</p><h3>Mes Forces et Accomplissements</h3><p>Au fil du temps, j’ai réussi à transformer ces obstacles en opportunités de croissance. Grâce à ma détermination, j’ai pu :</p><ul><li><strong>Maîtriser les hooks</strong> : La compréhension approfondie de useState, useEffect et même de hooks personnalisés m&#39;a permis de structurer mon code de manière plus claire et efficace.</li><li><strong>Construire des projets concrets</strong> : J’ai réalisé plusieurs projets, dont une application de gestion de contact ,une application de quiz. Ces projets m’ont permis de mettre en pratique les concepts appris et d’améliorer mes compétences en gestion d’état et en réactivité de l’interface.</li><li><strong>Adopter les meilleures pratiques</strong> : J’ai intégré le routage avec React Router, utilisé le Context API pour gérer des états globaux, et appris à optimiser les performances de mes applications.</li></ul><p>Chaque réussite était une source d’excitation, et voir mes applications prendre vie m’a motivé à repousser mes limites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dyh82co8OmK5-UuEu-3gbw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9OSQ6GwCTXfqaPUGswUpA.png" /><figcaption>quiz app</figcaption></figure><h3>L’Interaction avec Mon Tuteur</h3><p>Le soutien de mon tuteur a été déterminant dans mon apprentissage. Son approche pédagogique, à la fois rigoureuse et encourageante, m’a permis de comprendre des concepts complexes avec clarté. Lors d’une session, alors que je peinais à comprendre la gestion des effets secondaires avec useEffect, il a pris le temps de m&#39;expliquer en détail comment ce hook interagit avec le cycle de vie des composants. Grâce à ses explications illustrées par des exemples concrets, j&#39;ai pu assimiler cette notion qui me semblait auparavant obscure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yT2osBJ4xr7DQ0PsO9QexA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SHcFZbW-84zfA0QGPee5HQ.jpeg" /></figure><h3>Anecdotes et Moments Mémorables</h3><p>Je me souviens d’un projet interne donne par l’encadreur, où avec mes camarades, nous devrions relevé le défi de créer une application de quiz en utilisant une api pour les questions.le l’endemain j’ai ete choisir par l’encadreur pour expliquer mon travail a mes camarades de classe. C’était la confirmation que j’étais sur la bonne voie, que mes efforts portaient leurs fruits, que j’étais capable de m’approprier ce langage et de le maîtriser. Ce sentiment de connaissance, cette conscience d’avoir franchi une étape, a été renforcée par les questions et les réactions positives de mes camarades. C’était un véritable échange, un moment de partage et d’apprentissage mutuel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*StFbY1RaP4mmc173YDCprQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvXz4zNMXE1Rty85UUPMKA.jpeg" /></figure><h3>L’Environnement d’Apprentissage chez RebaseCodeCamp</h3><p>L’atmosphère au sein de RebaseCodeCamp est unique. Les locaux modernes, les espaces de coworking et l’esprit de collaboration ont créé un environnement propice à l’épanouissement. Les échanges réguliers avec mes pairs m’ont permis d’élargir mes perspectives et de découvrir de nouvelles façons de résoudre les problèmes. Cet environnement dynamique a été un véritable moteur de motivation, transformant chaque défi en opportunité d’apprentissage.</p><h3>Ce Que J’ai Gagné et Mes Préparations pour l’Avenir</h3><p>Grâce à ce module, j’ai acquis non seulement des compétences techniques solides en React JS, mais aussi des qualités personnelles indispensables : persévérance, esprit critique et capacité à travailler en équipe. J’ai appris à décomposer des problèmes complexes, à organiser mon code de manière modulable et à rester curieux face aux nouveautés du développement web.</p><p>Aujourd’hui, je me sens prêt à relever de nouveaux défis et à explorer des domaines encore plus ambitieux. Ce module m’a préparé à affronter les évolutions rapides du secteur et à continuer d’apprendre tout au long de ma carrière de développeur.</p><h3>Conclusion</h3><p>Mon expérience avec React JS chez RebaseCodeCamp a été une aventure transformatrice, riche en apprentissages techniques et en rencontres inspirantes. Entre les défis initiaux, les moments d’excitation, et l’appui précieux de mon tuteur et de mes camarades, j’ai pu forger une base solide pour ma carrière de développeur. Si vous souhaitez vous lancer dans l’apprentissage de React ou perfectionner vos compétences, je vous encourage vivement à explorer des environnements d’apprentissage collaboratifs comme celui de RebaseCodeCamp.</p><p>Chaque ligne de code écrite, chaque bug résolu, et chaque conseil partagé m’ont préparé pour les défis futurs, et je suis désormais prêt à écrire la prochaine page de mon parcours professionnel.</p><p><em>Merci de m’avoir lu ! N’hésitez pas à partager vos propres expériences et à poser vos questions en commentaire.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01c179fd5e27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mon Aventure JavaScript chez RebaseCodeCamp : Défis, Réussites et Découvertes]]></title>
            <link>https://medium.com/@diderotsielinou/mon-aventure-javascript-chez-rebasecodecamp-d%C3%A9fis-r%C3%A9ussites-et-d%C3%A9couvertes-ed2187410322?source=rss-8b07c70272d8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed2187410322</guid>
            <dc:creator><![CDATA[Diderot Sielinou]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 22:46:21 GMT</pubDate>
            <atom:updated>2025-04-18T22:52:29.749Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mon Aventure JavaScript chez RebaseCodeCamp : Défis, Réussites et Découvertes</h3><figure><img alt="javacript language" src="https://cdn-images-1.medium.com/max/1024/1*1PwdwbNjsOFhnmQg5QtkKw.png" /></figure><p>Mon parcours dans l’apprentissage de JavaScript chez RebaseCodeCamp a été une aventure riche en émotions, en découvertes et en enseignements. Dans cet article, je partage mon expérience personnelle, mes défis, mes accomplissements, ainsi que l’impact des interactions avec mon tuteur et mes camarades sur mon évolution, tant sur le plan technique que personnel.</p><h3>Les Défis Personnels de l’Apprentissage</h3><p>Dès le début, JavaScript m’a semblé être un univers à part entière, avec ses subtilités et ses concepts parfois abstraits. Un des premiers défis que j’ai rencontré fut la compréhension des <strong>promesses</strong>. Comprendre comment gérer l’asynchronisme en JavaScript, avec ses chaînes de .then() et ses async/await, a été un véritable casse-tête. J&#39;ai passé de nombreuses heures à lire la documentation, à tester du code et à déboguer des erreurs qui me semblaient incompréhensibles.</p><pre>let maPromesse = new Promise((resolve, reject) =&gt; {<br>    let success = true; // Simulons une opération réussie<br>    if (success) {<br>        resolve(&quot;Opération réussie !&quot;);<br>    } else {<br>        reject(&quot;Opération échouée !&quot;);<br>    }<br>});<br><br>maPromesse<br>    .then(result =&gt; console.log(result))<br>    .catch(error =&gt; console.log(error));</pre><p>Ces moments de frustration étaient parfois décourageants, mais ils m’ont appris à persévérer et à chercher des explications plus claires dans la pratique.</p><h3>Mes Forces et Accomplissements</h3><p>Malgré ces obstacles, j’ai découvert que ma curiosité et ma détermination étaient mes meilleurs atouts. J’ai pu réaliser plusieurs projets concrets, notamment :</p><ul><li><strong>Une application de gestion de tâches</strong>: ce projet ma permis d’assoir mes connaissances sur les base du langage javascripte (variables,functions,conditions,manipulation du DOM etc…).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*n6Ga6j8E_y7e0cMqJvqLjg.png" /></figure><ul><li><strong>Une application Movie DB</strong>: Ce projet m’a permis d’approfondir l’utilisation des promesses et des API, et d’appliquer mes connaissances sur des cas réels.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQgaaBHxfCoWlm-SVLQZbQ.png" /></figure><p>Ces projets m’ont permis de constater mes progrès et de renforcer ma confiance. Chaque fonctionnalité implémentée était une victoire, une preuve que je pouvais maîtriser des concepts complexes.</p><h3>L’Interaction avec Mon Tuteur</h3><p>L’une des dimensions les plus marquantes de mon expérience chez RebaseCodeCamp fut l’accompagnement personnalisé de mon tuteur. Son style d’enseignement, à la fois pédagogue et exigeant, m’a offert un contexte précieux pour progresser. Je me souviens d’une session où, alors que je peinais à comprendre l’ordre d’exécution des promesses, il a pris le temps de décortiquer le problème pas à pas avec des schémas et des exemples concrets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9_HDrseeu6X_suVumJgTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLx4cHZp-qtQejECmi7BHw.jpeg" /></figure><p>Ses explications claires et sa patience m’ont permis de surmonter mes difficultés, et ont transformé mes frustrations en moments d’apprentissage intense. Son soutien constant m’a motivé à continuer, même lorsque le chemin devenait ardu.</p><h3>L’Environnement d’Apprentissage</h3><p>L’environnement chez RebaseCodeCamp est dynamique et stimulant. Les locaux étaient équipés d’espaces de travail collaboratifs, propices aux échanges et à la concentration. Les interactions avec mes camarades ont enrichi mon expérience : nous partagions nos astuces, nos échecs, mais aussi nos succès. Cette ambiance bienveillante et compétitive à la fois m’a permis de repousser mes limites et de grandir en tant que développeur.</p><h3>Ce Que J’ai Gagné</h3><p>Grâce à ce module, j’ai non seulement acquis une solide maîtrise de JavaScript, mais j’ai aussi gagné en résilience et en confiance. J’ai appris à affronter mes doutes, à chercher des solutions innovantes et à persévérer dans l’adversité. Techniquement, la compréhension approfondie des <strong>promesses</strong> et des autres concepts asynchrones a ouvert la voie à la réalisation de projets plus ambitieux. Personnellement, j’ai découvert la valeur du travail collaboratif et l’importance de se soutenir mutuellement dans un parcours d’apprentissage exigeant.</p><h3>Conclusion</h3><p>Mon expérience chez RebaseCodeCamp a été une aventure transformative. Entre les défis techniques, les réussites éclatantes et l’accompagnement exceptionnel de mon tuteur, j’ai appris bien plus que le langage JavaScript. J’ai découvert une communauté d’apprenants passionnés, un environnement où chaque difficulté se transforme en opportunité de croissance. Aujourd’hui, je me sens prêt à relever de nouveaux défis, armé de compétences solides et d’une motivation sans faille pour continuer à explorer le monde fascinant du développement web.</p><p>Si vous envisagez de vous lancer dans l’apprentissage de JavaScript ou que vous cherchez à booster votre carrière, je vous encourage à explorer des programmes comme celui de RebaseCodeCamp. Les leçons techniques et les expériences humaines que vous y vivrez vous prépareront à conquérir les défis futurs.</p><p><em>Merci de m’avoir lu, et n’hésitez pas à partager vos propres expériences ou à poser vos questions en commentaire !</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed2187410322" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>