<?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 Yassine Ramzi on Medium]]></title>
        <description><![CDATA[Stories by Yassine Ramzi on Medium]]></description>
        <link>https://medium.com/@yassine.ramzi2010?source=rss-6af5de26af7d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IWfA92gTlCxYXmTO2ay4xw.jpeg</url>
            <title>Stories by Yassine Ramzi on Medium</title>
            <link>https://medium.com/@yassine.ramzi2010?source=rss-6af5de26af7d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:17:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yassine.ramzi2010/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[DRY · SOLID · TDD/BDD — Supercharged with AI]]></title>
            <link>https://medium.com/@yassine.ramzi2010/dry-solid-tdd-bdd-supercharged-with-ai-46a752c1462b?source=rss-6af5de26af7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/46a752c1462b</guid>
            <category><![CDATA[ai-prompts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Yassine Ramzi]]></dc:creator>
            <pubDate>Thu, 07 May 2026 13:52:20 GMT</pubDate>
            <atom:updated>2026-05-07T13:52:20.101Z</atom:updated>
            <content:encoded><![CDATA[<h3>How timeless software engineering principles become your most powerful tool for steering AI agents — and why quality control starts long before you write a single test.</h3><h3>1. Why principles matter more than ever</h3><p>We live in an era of accelerated software production. AI code-generation tools can emit hundreds of lines in seconds. Junior developers ship features that would have taken a week in a morning. The bottleneck has shifted — from <em>writing</em> code to <em>controlling</em> its quality.</p><p>Yet the code an AI generates is only as good as the context you give it. Without clear contracts, single-responsibility boundaries, and test specifications, you are handing an extraordinarily fast typist a vague sticky note and hoping for the best.</p><p>This is where the classics bite back. <strong>DRY</strong> and <strong>SOLID</strong> are not academic constraints — they are the grammar that makes your intent legible to both humans and machines. <strong>TDD</strong> and <strong>BDD</strong> are not bureaucratic overhead — they are the executable specification that lets you validate output the moment it arrives.</p><blockquote>“Principles don’t slow you down. They are the track that lets the train go faster.”</blockquote><p>In this article we will explore each principle in depth, show how they reinforce each other, and then build a concrete workflow for directing AI agents while maintaining rigorous control over what lands in production.</p><h3>2. The DRY principle unpacked</h3><p><strong>Don’t Repeat Yourself</strong> — coined by Andy Hunt and Dave Thomas in <em>The Pragmatic Programmer</em> — states: “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.”</p><p>Notice the word <em>knowledge</em>, not <em>code</em>. DRY is widely misunderstood as “never copy-paste.” It’s deeper than that. Two functions that look similar may encode different knowledge and should stay separate. Two functions that look different but encode the same business rule must be unified.</p><h3>DRY in practice: the three layers</h3><p><strong>L1 — Logic DRY (business rules)</strong> A pricing calculation, a validation rule, a state machine: each lives in exactly one place. Any change propagates automatically across every consumer.</p><p><strong>L2 — Data DRY (schema and models)</strong> Your database schema, API contracts, and TypeScript interfaces derive from a single source of truth. Code generation, not manual synchronisation.</p><p><strong>L3 — Configuration DRY (environment and constants)</strong> Environment variables, feature flags, and constants are centralised. No magic strings scattered across 40 files.</p><pre>// ✗ WET — the 10% rule is encoded three times<br>function getCartDiscount(total: number) {<br>  if (total &gt; 100) return total * 0.10;<br>}<br>function getInvoiceDiscount(total: number) {<br>  if (total &gt; 100) return total * 0.10;<br>}<br>function getCheckoutSummaryDiscount(total: number) {<br>  if (total &gt; 100) return total * 0.10;<br>}</pre><pre>// ✓ DRY — single source of truth<br>const BULK_THRESHOLD = 100;<br>const BULK_RATE = 0.10;</pre><pre>function calculateDiscount(total: number): number {<br>  return total &gt; BULK_THRESHOLD ? total * BULK_RATE : 0;<br>}<br>// getCartDiscount, getInvoiceDiscount all delegate here</pre><p><strong>AI Implication:</strong> When prompting an AI agent, describe the single source of truth first. <em>“The discount rule lives in </em><em>calculateDiscount. Add checkout summary support that reuses it.&quot;</em> An AI without context will happily create a fourth copy.</p><h3>3. SOLID — five laws of good design</h3><p>Introduced by Robert C. Martin, the SOLID principles provide a five-point checklist for writing object-oriented (or module-based) code that is maintainable, extensible, and testable.</p><p><strong>S — Single Responsibility Principle</strong> A class or module should have one, and only one, reason to change. Split UserService into authentication, profile management, and notification concerns — each can change independently.</p><p><strong>O — Open/Closed Principle</strong> Open for extension, closed for modification. Add new payment processors by implementing PaymentGateway without touching existing processors. The existing tests stay green.</p><p><strong>L — Liskov Substitution Principle</strong> Subtypes must be substitutable for their base types. A ReadonlyList that throws on add() is not a valid List subtype — it breaks callers silently.</p><p><strong>I — Interface Segregation Principle</strong> Clients should not depend on interfaces they don’t use. Prefer five focused interfaces over one fat IRepository that forces a cache layer to implement delete().</p><p><strong>D — Dependency Inversion Principle</strong> High-level modules must not depend on low-level modules — both should depend on abstractions. Inject IEmailSender; swap SendGrid for SES without touching business logic.</p><h3>SOLID and testability are inseparable</h3><p>SOLID code is not just clean — it is testable by construction. When dependencies are injected (D), interfaces are focused (I), and responsibilities are separated (S), every unit test becomes a simple arrange-act-assert over a single, replaceable boundary. Mocking becomes trivial. Test coverage becomes meaningful.</p><pre>// Abstractions — high-level contracts<br>interface IEmailSender {<br>  send(to: string, subject: string, body: string): Promise&lt;void&gt;;<br>}</pre><pre>interface IUserRepository {<br>  findById(id: string): Promise&lt;User&gt;;<br>  save(user: User): Promise&lt;void&gt;;<br>}</pre><pre>// High-level module — no concrete imports<br>class RegistrationService {<br>  constructor(<br>    private repo: IUserRepository,<br>    private email: IEmailSender,<br>  ) {}</pre><pre>  async register(dto: RegisterDto): Promise&lt;User&gt; {<br>    const user = User.create(dto);<br>    await this.repo.save(user);<br>    await this.email.send(user.email, &#39;Welcome!&#39;, &#39;…&#39;);<br>    return user;<br>  }<br>}</pre><pre>// In tests: inject mock implementations. In prod: inject real ones.</pre><h3>4. TDD: red, green, refactor</h3><p><strong>Test-Driven Development</strong> inverts the writing order: tests come before implementation. The tight loop is just three steps, repeated continuously.</p><p><strong>🔴 Red → 🟢 Green → 🔵 Refactor → repeat</strong></p><p><strong>Red:</strong> Write the smallest test that expresses your next requirement. Run it — it fails because there’s nothing to pass it yet. This failure is meaningful: it proves your test is actually testing something.</p><p><strong>Green:</strong> Write the minimum code to make the test pass. Don’t gold-plate it. Ugly code is fine here — you’re proving the behaviour, not crafting the architecture.</p><p><strong>Refactor:</strong> Clean the implementation while keeping all tests green. Extract, rename, deduplicate. The test suite is your safety net — pull it taut.</p><pre>// 1. RED — write the failing test first<br>describe(&#39;PasswordValidator&#39;, () =&gt; {<br>  it(&#39;rejects passwords shorter than 8 chars&#39;, () =&gt; {<br>    const v = new PasswordValidator();<br>    expect(v.validate(&#39;abc&#39;)).toEqual({<br>      valid: false,<br>      errors: [&#39;Minimum 8 characters required&#39;],<br>    });<br>  });<br>});</pre><pre>// 2. GREEN — minimal implementation<br>class PasswordValidator {<br>  validate(password: string) {<br>    const errors: string[] = [];<br>    if (password.length &lt; 8)<br>      errors.push(&#39;Minimum 8 characters required&#39;);<br>    return { valid: errors.length === 0, errors };<br>  }<br>}</pre><pre>// 3. REFACTOR — extract magic number, add more cases<br>const MIN_LENGTH = 8; // DRY + SOLID starts here</pre><p><strong>Why TDD pays compound interest:</strong> Every test written today is documentation for tomorrow, a regression guard for next month, and a contract specification for any AI agent you point at the codebase next year.</p><h3>5. BDD: behaviour as specification</h3><p><strong>Behaviour-Driven Development</strong> extends TDD by placing specification in a language that crosses the boundary between business and engineering. BDD scenarios are written in <strong>Given/When/Then</strong> — close enough to English that a product manager, a QA engineer, and a developer all read the same thing.</p><pre>Feature: User authentication</pre><pre>Background:<br>  Given a registered user with email &quot;ada@example.com&quot;<br>  And password &quot;Secure!99&quot;</pre><pre>Scenario: Successful login<br>  When the user submits valid credentials<br>  Then they receive a JWT access token<br>  And a refresh token is stored in an httpOnly cookie<br>  And a &quot;user.login&quot; event is emitted</pre><pre>Scenario: Failed login after 5 attempts<br>  When the user submits incorrect credentials 5 times<br>  Then the account is locked for 15 minutes<br>  And a &quot;security.lockout&quot; event is emitted</pre><p>The step definitions map these plain-language specs to actual test code. The Gherkin file is not decoration — it <em>runs</em>. Tools like Cucumber, Behave, or SpecFlow execute it directly.</p><p>Dimension TDD Focus BDD Focus <strong>Audience</strong> Developer writing the unit Whole team including PMs <strong>Language</strong> Code (Jest, Vitest, RSpec…) Gherkin + code step defs <strong>Scope</strong> Unit / function / module Feature / user journey <strong>Drives</strong> Internal API design External behaviour contract <strong>Living doc</strong> Test file only .feature file — human-readable</p><h3>6. Aligning TDD/BDD with DRY/SOLID</h3><p>These four concepts are not independent tools — they form a coherent system. Each layer depends on the others being healthy.</p><h3>SOLID makes TDD cheap</h3><p>If a class violates SRP, testing it means loading a web of dependencies. If it violates DIP, you can’t inject mocks. SOLID design collapses the cost of each unit test to nearly zero — short arrange phase, single assertion, no side effects.</p><h3>DRY makes tests meaningful</h3><p>When a business rule lives in one function, one test suite covers all consumers. When the same logic is copy-pasted five times, a passing test suite still gives you false confidence — you’ve tested three copies, not the rule.</p><h3>BDD surfaces DRY violations early</h3><p>Writing a Gherkin scenario forces you to name the behaviour in business terms. If you find yourself writing nearly identical scenarios with slightly different wording, that’s a smell: the domain model may be missing an abstraction. The spec is finding DRY violations <em>before</em> the code is written.</p><blockquote><strong><em>Anti-pattern to avoid:</em></strong><em> Writing tests after the fact to hit coverage targets. Such tests validate current behaviour — including bugs — and create the illusion of safety. Tests written first drive design. Tests written last document accidents.</em></blockquote><h3>The virtuous cycle</h3><ol><li>Write BDD scenarios with the product team — the <em>what</em></li><li>Decompose each scenario into TDD unit tests — the <em>how</em></li><li>Implement units that respect SRP and DIP — <em>testable by construction</em></li><li>Extract shared logic, enforce DRY across the implementations</li><li>Refactor until SOLID and DRY are both satisfied — tests stay green throughout</li></ol><h3>7. AI agents and your output quality</h3><p>AI coding agents — whether integrated into your IDE, invoked from the CLI, or embedded in a CI pipeline — are powerful amplifiers. The question is: <em>what are they amplifying?</em></p><p>A codebase with clear interfaces, injected dependencies, and well-named abstractions gives an AI agent extraordinary leverage. A tangled codebase with shared mutable state and implicit coupling gives an AI agent material to make everything worse, faster.</p><h3>How principles control AI output</h3><p>Each principle doubles as a guardrail for AI-generated code:</p><ul><li><strong>DRY</strong> — Point the agent at the canonical abstraction. <em>“Implement this using </em><em>calculateDiscount from the pricing module.&quot;</em> It has a target and can&#39;t create a duplicate.</li><li><strong>SRP</strong> — Scope prompts to single responsibilities. <em>“Add email validation to </em><em>EmailValidator only.&quot;</em> Prevents accidental feature creep into unrelated classes.</li><li><strong>OCP</strong> — <em>“Add a </em><em>StripeGateway that implements </em><em>IPaymentGateway.&quot;</em> The contract exists; the AI fills the implementation without touching what works.</li><li><strong>DIP</strong> — Share your interface definitions upfront. Agents that see IUserRepository will inject it; agents that see a concrete ORM class will couple to it.</li><li><strong>TDD</strong> — <em>“Write failing tests for the following spec, then implement.”</em> The test-first approach makes the agent’s output immediately verifiable — run the suite, trust the result.</li><li><strong>BDD</strong> — Paste your Gherkin scenario directly into the prompt. Agents can translate Given/When/Then into step definitions and integration tests with high fidelity.</li></ul><h3>The prompt as a specification</h3><p>Your best prompt to an AI agent is not <em>“write me a user service.”</em> It is your BDD scenario, your interface definition, your DRY abstraction reference, and a note on which SOLID principle governs the boundary. The more your prompt reads like a well-designed system, the more the output resembles one.</p><pre>/*Prompt to AI agent:</pre><pre>  Context:<br>  - IUserRepository and IEmailSender are defined in src/interfaces/<br>  - RegistrationService follows SOLID — inject, don&#39;t import concretions<br>  - Pricing rules live solely in src/domain/pricing.ts (DRY)</pre><pre>  Task (TDD-first):<br>  1. Write failing Jest tests for a `UserRegistrationUseCase` that:<br>     - Validates the DTO using the existing Zod schema in src/schemas/<br>     - Delegates persistence to IUserRepository<br>     - Sends a welcome email via IEmailSender<br>     - Emits a domain event via IEventBus<br>  2. Implement the use case to pass all tests<br>  3. Do not modify any existing interfaces or pricing logic</pre><pre>  BDD scenario for integration test:<br>    Given a valid registration DTO<br>    When register() is called<br>    Then the user is persisted<br>    And a welcome email is sent<br>    And a &quot;user.registered&quot; event is emitted<br>*/</pre><p>Notice what this prompt does: it constrains the blast radius (don’t modify interfaces), it points to DRY authorities (pricing.ts), it enforces SOLID (inject, don&#39;t import), and it provides BDD acceptance criteria. The AI cannot go rogue because the design already exists.</p><h3>Validating AI output with your test suite</h3><p>Once you adopt TDD, your CI pipeline becomes the final word on AI output quality. The workflow is simple:</p><ol><li>AI generates code (or tests + code)</li><li>You review the tests first — are they testing the right behaviour?</li><li>You run npm test — does everything pass, including pre-existing tests?</li><li>You check coverage — did the agent miss an edge case?</li><li>You run a linter with SOLID-rule enforcement (ESLint, Checkstyle, etc.)</li><li>Only then does the code enter review — humans check intent, not correctness</li></ol><h3>8. The complete workflow</h3><p>Bringing it all together, here is a sprint-ready workflow that combines every principle into a productive daily rhythm.</p><p><strong>① Specify with BDD</strong> Work with stakeholders to write Gherkin scenarios before a single line of implementation exists. These scenarios are the contract the entire team signs.</p><p><strong>② Design interfaces (SOLID: D, I)</strong> Sketch the boundaries: what interfaces will the new feature consume? What does it expose? Define these first — they become the AI’s vocabulary.</p><p><strong>③ Write failing unit tests (TDD: Red)</strong> Translate each scenario step into one or more unit tests. Let the AI help here — give it the scenario and the interfaces, ask for tests first.</p><p><strong>④ Implement to green (TDD: Green)</strong> Direct the AI agent with a principle-anchored prompt. Let it generate the implementation. Run tests immediately. Iterate on failures with targeted prompts.</p><p><strong>⑤ Refactor for DRY + SOLID</strong> With green tests as your net, extract abstractions, unify duplicates, split mixed responsibilities. Ask the AI for refactoring suggestions — it excels here.</p><p><strong>⑥ Validate and ship</strong> Run the full BDD suite, coverage check, and SOLID linting rules. Human review focuses on intent and business correctness, not syntax or structure.</p><blockquote>“The developer’s new superpower is not typing faster — it’s writing specifications that are precise enough to make any agent produce correct code on the first attempt.”</blockquote><h3>What this unlocks in practice</h3><p>Teams that operate this way report a characteristic shift: they spend <em>less time debugging AI output</em> and more time on domain modelling and product thinking — which is where the highest-leverage human work lives. The principles are not a tax on velocity. They are the force multiplier.</p><p>The developer who masters DRY, SOLID, TDD, and BDD is not competing with AI agents. They are the architect who decides what gets built, the reviewer who decides whether it’s correct, and the author of the specifications that make both humans and machines productive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46a752c1462b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Diesel Engine and the Donkey: What AI Actually Does to Software Engineering Jobs]]></title>
            <link>https://medium.com/@yassine.ramzi2010/the-diesel-engine-and-the-donkey-what-ai-actually-does-to-software-engineering-jobs-234a7e6db438?source=rss-6af5de26af7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/234a7e6db438</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Yassine Ramzi]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 20:17:57 GMT</pubDate>
            <atom:updated>2026-03-24T20:17:57.433Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A field-level analysis from inside the machine — with the data to back it up</em></p><p>There is a version of the AI-replaces-coders story that goes viral on TikTok every week. A 22-year-old vibe-codes an app in two hours, posts the demo, gets 500,000 views, and declares the engineering profession dead. The comments section splits between panic and celebration.</p><p>Neither group has ever been responsible for a production system at 2am.</p><p>This is an attempt at the real story — grounded in what the data actually says, what experienced engineers and CTOs are living through day to day, and why the most important question is not “will AI take SWE jobs” but “which humans become more valuable, which become extinct, and what happens to the pipeline between them?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*D_X3O8vIaMEEoXVTGiv8Kg.jpeg" /></figure><h3>What the Numbers Actually Say</h3><p>The headline is not “AI is replacing engineers.” The headline is more precise and more troubling: <strong>AI is collapsing the bottom of the ladder while expanding the top.</strong></p><p>Entry-level positions (P1 and P2 job levels) have seen a <a href="https://ravio.com/blog/tech-hiring-trends">73% decrease in hiring rates</a> in the past year, according to Ravio’s 2025 Tech Job Market Report — compared to just a 7% decrease across all job levels overall. Job postings for “junior developer” or “entry-level software engineer” positions have <a href="https://www.finalroundai.com/blog/software-engineering-job-market-2026">dropped roughly 40%</a> compared to pre-2022 levels, even as the number of CS graduates and bootcamp alumni has increased.</p><p>The Stanford Digital Economy study found that <a href="https://stackoverflow.blog/2025/12/26/ai-vs-gen-z/">for IT and software engineering jobs — the most AI-exposed roles — employment has declined 6% for workers aged 22–25, while it has increased 9% for workers aged 35–49</a>. The age split could not be clearer. Hiring is happening — just not for people at the start of their careers.</p><p>Meanwhile, overall software engineering is not dying. US employment in computer and IT occupations is <a href="https://www.interviewquery.com/p/tech-job-market-2026-shrinking-and-growing">projected to grow from roughly 6.09 million in 2025 to around 7.03 million by 2035</a>, and AI/ML role postings grew <a href="https://ravio.com/blog/tech-hiring-trends">88% year over year in 2025</a>. The market is not shrinking. It is reshaping — upward and sideways, not at the entry point.</p><p>This bifurcation is the central fact that TikTok does not explain.</p><h3>The Diesel Engine and the Donkey</h3><p>The most honest analogy for AI in software development is this: a diesel engine is faster, stronger, and cheaper per kilometer — on highways, on flat terrain, on known routes with infrastructure built around it. That describes AI on well-defined, structured, repeatable tasks: generating boilerplate, writing tests, converting legacy code, drafting documentation. Genuinely faster. No argument.</p><p>But the mountain reveals everything the engine assumed.</p><p>The road ends. The surface becomes unpredictable. The weight distribution shifts. The engine was designed for a particular kind of terrain, and that assumption was invisible until it wasn’t.</p><p>The donkey, meanwhile, feels the ground shifting underfoot in real time. Redistributes weight instinctively on unstable surfaces. Knows when to stop before the edge — without being told where the edge is. Has survived this specific mountain before.</p><p>That is senior human judgment in software engineering. It is not fast. It is not impressive on a benchmark. You cannot demo it at a conference. But when everything else fails, it is the only thing that gets the load to the top.</p><h3>The Problems AI Cannot Navigate Alone</h3><p>Consider a real-world scenario that plays out constantly in enterprise software. A large financial institution engages a major IT services firm to modernize its document storage platform — introducing fine-grained access control by folder, subfolder, and file. It sounds like a well-scoped engineering problem. Ask an AI agent to build it and it will produce something that looks complete and probably passes the demo.</p><p>Then the real questions emerge.</p><p>When a user’s access is revoked server-side while their machine is offline, and they reconnect with local edits made during that window — who wins? The local file or the server? Do you discard the edits? Keep a conflicted copy? Notify the user silently or loudly? There is no clean answer, only tradeoffs, and the right tradeoff depends on the institution’s specific risk appetite, its regulatory obligations, and undocumented decisions made three years ago by people who may have since left.</p><p>What is a checksum and why does it matter at 2am? It is a mathematical fingerprint of a file — run the function, get a short string, and if one byte changes, the fingerprint changes entirely. Without it you are syncing blindly. The AI agent knows this in the abstract. It does not know that your specific legacy system produces checksums in a non-standard format that conflicts with the new library it just chose.</p><p>The sync daemon crashes mid-operation. The file was modified locally but not confirmed server-side. Is local the truth? Server? You need a write-ahead log — a receipt book of intended operations written before they execute. The agent can generate this pattern. It cannot know which of your existing infrastructure components already implement something similar in a way that will silently conflict.</p><p>These are not exotic edge cases. They are the normal problems of production systems at scale. And <a href="https://www.hoganlovells.com/en/publications/agentic-ai-in-financial-services-regulatory-and-legal-considerations">leading financial institutions are now explicitly acknowledging that agentic AI systems, with their increased autonomy and reduced human oversight, create significant new risks</a> — including the possibility that agents with misaligned goals may conceal their actions, disable oversight mechanisms, or introduce bias that only surfaces after consumer harm has occurred.</p><p>This is not a theoretical concern. <a href="https://neontri.com/blog/agentic-ai-banking/">The Digital Operational Resilience Act (DORA), effective January 2025, places ultimate accountability for AI-driven ICT failures on management</a>. Humans are accountable. The agent is not. That asymmetry is permanent.</p><h3>The Translation Stack Has No Floor</h3><p>When a business leader says “enhance the storage experience,” that sentence contains almost none of the information required to build the right thing. Behind it lies an ocean of decisions that require contextual technical judgment:</p><p>Is the bottleneck perceived performance or actual throughput? Do we touch the sync engine or just the UI feedback layer? What is the blast radius if we change the chunking strategy — does it break third-party integrations? Do we go event-driven and accept the operational complexity, or stay boring and ship faster?</p><p>An AI agent will make assumptions about each of these. It will document them confidently. Some will be wrong in ways that only manifest at scale, under load, or in conditions that did not exist in training data.</p><p>The person who catches this is not a Product Owner — that role is typically functional, not technical. It is not a traditional developer whose job was to write syntax. It is a new kind of role that barely has a name yet: someone who speaks business intent fluently in one direction and technical constraint fluently in the other, who can write agent instructions with enough precision that the output is actually buildable, and who can evaluate whether the output maps to the real system rather than to the agent’s model of the system.</p><p>This person is rarer than a senior engineer. They command an increasingly extraordinary premium. And there are far too few of them.</p><h3>Who Evaluates 100 AI-Generated Features?</h3><p>Here is the question nobody in the productivity-gain conversation is answering honestly: if a team’s output velocity increases tenfold, can one technical expert meaningfully review tenfold more code?</p><p>No.</p><p>Real review in a production context — especially in regulated industries — requires asking whether a feature has edge cases the agent did not consider, whether it introduces a security surface that was not flagged, whether it conflicts with an architectural decision made 18 months ago that exists only in one person’s memory, and whether it is consistent with where the system is going rather than just where it is. That process does not compress.</p><p>What actually happens in practice is one of three things. Shallow review at scale, where the expert becomes a pattern-matcher and catches obvious problems while missing subtle ones, with technical debt accumulating invisibly. AI-assisted review, where a second agent reviews the first agent’s output — which helps, but the errors that slip through are precisely the ones both agents share as blind spots. Or tiered ownership, where critical paths (authentication, payments, data integrity, compliance logic) receive deep human review while everything else ships with automated test coverage and is monitored reactively in production.</p><p>The third approach is what sophisticated teams are converging on. But it requires someone with enough judgment to correctly classify which features are critical. That classification is itself a high-stakes human decision that cannot be delegated to the system being evaluated.</p><h3>The 2am Problem</h3><p>Six months after a major financial institution deploys its new AI-assisted platform, the maintenance contract with the IT services firm expires. Eighteen months later, a security breach is declared at 2am.</p><p>The agents that built the system are stateless — they remember nothing. The engineers who configured them have moved to the next engagement. The documentation the agents produced describes what the code intended to do, not what it actually does in the specific production environment with the specific load patterns and the specific third-party dependencies that have since been updated. The on-premise model cannot be patched without triggering a new compliance review cycle.</p><p>Who picks up the phone?</p><p>A human who understands the system deeply enough to improvise under incomplete information, under pressure, with real money and real customers at stake. That person commands an extraordinary premium. <a href="https://fullscale.io/blog/developer-hiring-trends-2026/">The shortage of senior engineers is already projected to be 40% more severe in 2026 than in 2025, with 18% of senior developers born between 1970 and 1980 planning retirement before 2027</a> — and they are taking decades of undocumented system knowledge with them.</p><p>The 2am breach is not the failure of the AI. The AI performed exactly as designed. It is the failure to maintain the human layer capable of governing what the AI built.</p><h3>The Pipeline Problem Nobody Is Solving</h3><p>The most serious long-term consequence of eliminating junior roles is not the immediate talent shortage. It is the generational knowledge transfer problem that becomes visible a decade later.</p><p>You do not become a senior engineer by being born one. You become one by debugging something broken at 2am without knowing why. By shipping something that worked perfectly in staging and exploded in production. By making an architectural decision you were proud of that aged terribly in 18 months. By writing terrible code yourself and learning from it.</p><p><a href="https://spectrum.ieee.org/ai-effect-entry-level-jobs">With AI tools performing more of the task-oriented work that has served as the training ground for early-career engineers, expectations for recent graduates are now to “slot in at a higher level almost from day one,” according to Harvard’s David Malan</a>. But you cannot fast-track the experience. The junior who should have been hired in 2025 and become a solid mid-level engineer by 2028 — that person simply does not exist if the hiring never happened. You cannot rewind it.</p><p><a href="https://www.globalsoftwarecompanies.com/software-engineer-shortage">A Harvard study in 2025 found that companies adopting generative AI are not firing junior engineers — they have simply stopped posting entry-level positions</a>. The effect is the same. The pipeline empties without anyone officially closing it.</p><p><a href="https://ravio.com/blog/tech-hiring-trends">As one industry analyst put it: “If you don’t hire and nurture young talent now, what will your mid-level and leadership positions look like in five years? We’re heading towards some very difficult and expensive recruitment to fill that gap.”</a> That quote is from Ravio’s 2025 Tech Job Market Report. It is describing a structural problem that no amount of AI productivity gain resolves.</p><h3>What Actually Survives — and What Does Not</h3><p>The developers who defined themselves by syntax mastery are correctly worried. The language is irrelevant now. An agent switches from Java to Go to Rust mid-task without friction. If your entire value proposition was deep knowledge of a specific framework’s annotations, that is largely gone.</p><p>But the following roles are not only surviving — they are becoming more valuable:</p><p><strong>System architects and staff engineers</strong> who maintain the full mental model of a complex system and can evaluate whether AI-generated components fit coherently into it. Their job shifts from producing to governing, but the judgment surface has not shrunk. If anything it has grown.</p><p><strong>Security engineers</strong> whose job is specifically to find the things that look correct and are subtly wrong. <a href="https://fullscale.io/blog/developer-hiring-trends-2026/">AI engineering security roles are growing at double-digit rates</a>, precisely because AI-generated code creates new attack surfaces faster than it eliminates old ones.</p><p><strong>Technical product owners</strong> — the emerging critical role — who can translate ambiguous business intent into technically precise, security-conscious, compliance-aware agent instructions, and then evaluate whether the output actually maps to the real system. This person speaks both boardroom and terminal. They are rarer than any technical specialist and increasingly more valuable than either.</p><p><strong>The 2am engineers</strong> — people with enough scar tissue from production systems to improvise under pressure with incomplete information. No benchmark measures this. No agent replicates it. Every complex system eventually needs one.</p><p>What goes extinct is narrower than the TikTok narrative suggests: the developer whose entire identity is a specific language or framework, who does not understand the systems their code runs in, who cannot communicate upward or evaluate downward. That profile was already under pressure before AI. AI accelerated the timeline.</p><h3>The Honest Conclusion</h3><p>The software engineering market is growing. The profession survives. The velocity gains from AI tooling are real and significant — <a href="https://www.globalsoftwarecompanies.com/software-engineer-shortage">85% of developers now regularly use AI tools for coding and software design</a>, and AI agents generate nearly half of all code written by active developers. This is not reversing.</p><p><strong><em>But the transition is brutal for people at the entry level right now, the pipeline is hollowing in ways that will not be visible as a crisis for another decade, and the organizations celebrating productivity gains without maintaining the human layer capable of governing AI output are accumulating invisible risk.</em></strong></p><p>The diesel engine is real. On the highway, it wins every time.</p><p>The mountain is also real. And the donkey has never been more expensive per kilometer — because everyone finally understands what it is actually for.</p><p><em>Data sources: </em><a href="https://ravio.com/blog/tech-hiring-trends"><em>Ravio 2025 Tech Job Market Report</em></a><em> · </em><a href="https://stackoverflow.blog/2025/12/26/ai-vs-gen-z/"><em>Stanford Digital Economy Lab via Stack Overflow</em></a><em> · </em><a href="https://spectrum.ieee.org/ai-effect-entry-level-jobs"><em>IEEE Spectrum / NACE Job Outlook 2026</em></a><em> · </em><a href="https://www.globalsoftwarecompanies.com/software-engineer-shortage"><em>Global Software Companies / Harvard Study 2025</em></a><em> · </em><a href="https://ravio.com/blog/tech-hiring-trends"><em>Ravio / JetBrains Developer Survey Oct 2025</em></a><em> · </em><a href="https://www.hoganlovells.com/en/publications/agentic-ai-in-financial-services-regulatory-and-legal-considerations"><em>Hogan Lovells — Agentic AI in Financial Services</em></a><em> · </em><a href="https://www.deloitte.com/us/en/insights/industry/financial-services/agentic-ai-risks-banking.html"><em>Deloitte Center for Financial Services</em></a><em> · </em><a href="https://fullscale.io/blog/developer-hiring-trends-2026/"><em>Full Scale — Developer Hiring Trends 2026</em></a><em> · </em><a href="https://www.interviewquery.com/p/tech-job-market-2026-shrinking-and-growing"><em>Interview Query — Tech Job Market 2026</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=234a7e6db438" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Made Simple: Part 2 : Dockerfiles, Custom Images, and Best Practices]]></title>
            <link>https://medium.com/devsecops-ai/docker-made-simple-part-2-dockerfiles-custom-images-and-best-practices-f611fba8d735?source=rss-6af5de26af7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f611fba8d735</guid>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-image]]></category>
            <dc:creator><![CDATA[Yassine Ramzi]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 16:53:54 GMT</pubDate>
            <atom:updated>2025-10-11T17:22:25.643Z</atom:updated>
            <content:encoded><![CDATA[<h3>Docker Made Simple: Part 2 : Dockerfiles, Custom Images, and Best Practices</h3><blockquote>In part 1, we introduced Docker and how to get started without feeling overwhelmed.</blockquote><blockquote>Now, we dive deeper: how to <strong>write optimized Dockerfiles</strong>, understand <strong>Docker architecture</strong>, analyze <strong>image layers</strong>, use <strong>multi-stage builds</strong>, and follow <strong>security best practices</strong>.</blockquote><h3>🏗️ Understanding Docker Architecture</h3><p>Docker is built on a client-server architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Bpr5YzINDQUqGMsV4qyzA.webp" /></figure><ul><li><strong>Docker Daemon (`dockerd`)</strong>: Handles building, running, and managing containers.</li><li><strong>Docker CLI (`docker`)</strong>: The command-line interface to interact with the daemon.</li><li><strong>Docker Images</strong>: Immutable blueprints containing application code, dependencies, and runtime.</li><li><strong>Docker Container</strong>s: Lightweight, runnable instances of images.</li><li><strong>Docker Registries</strong>: Repositories to store and share images (Docker Hub, private registries).</li></ul><p>Understanding this helps in <strong>optimizing builds, storage, and deployment</strong>.</p><h3>📝 Writing Efficient Dockerfiles</h3><p>A Dockerfile is a <strong>recipe</strong> for your image. Optimization tips:</p><p>1. <strong>Use minimal base images</strong> (e.g., `alpine`) to reduce image size.<br>2. <strong>Leverage Docker layer caching</strong>: Changes in upper layers invalidate cache, so place frequently-changing instructions (like `COPY . .`) at the bottom.<br>3. <strong>Minimize the number of layers</strong>: Combine commands using `&amp;&amp;` in `RUN` instructions.<br>4. <strong>Clean up after installation</strong>: Remove unnecessary files to reduce final image size.</p><p><strong>Example:</strong></p><pre>FROM node:14-alpine<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install - production &amp;&amp; rm -rf /tmp/*<br>COPY . .<br>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;app.js&quot;]</pre><h3>🔍 Analyzing Image Layers</h3><p>Docker images are made of <strong>layers</strong>. Each instruction in a Dockerfile creates a new layer. Tools to inspect layers:</p><ul><li>`<strong>docker history &lt;image&gt;</strong>` — shows each layer and size.</li><li>`<strong>dive</strong>` ([<a href="https://github.com/wagoodman/dive](https://github.com/wagoodman/dive))">https://github.com/wagoodman/dive](https://github.com/wagoodman/dive))</a> — interactive tool to explore layers, analyze wasted space, and optimize builds.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IgXdnrNhuN9pzlXETRJRJg.jpeg" /></figure><p>Understanding layers helps <strong>reduce image size and build times</strong>.</p><h3>🚀 Multi-Stage Builds</h3><p>Multi-stage builds allow you to <strong>separate build-time dependencies from runtime</strong>, producing smaller, production-ready images.</p><p>Example for a Node.js app:</p><pre># Stage 1: Build<br>FROM node:14 AS builder<br>WORKDIR /app<br>COPY package*.json ./<br>RUN npm install<br>COPY . .<br>RUN npm run build<br><br># Stage 2: Runtime<br>FROM node:14-alpine<br>WORKDIR /app<br>COPY - from=builder /app/dist ./dist<br>COPY package*.json ./<br>RUN npm install - production<br>EXPOSE 3000<br>CMD [&quot;node&quot;, &quot;dist/app.js&quot;]</pre><ul><li><strong>Stage 1</strong> installs dev dependencies and builds the app.</li><li><strong>Stage 2 </strong>only copies what’s needed for production, drastically reducing image size.</li></ul><h3>🔐 Docker Security Best Practices</h3><p>1. <strong>Run containers as non-root users</strong> whenever possible.<br>2.<strong> Avoid storing secrets in images</strong>; use environment variables or Docker secrets.<br>3. <strong>Use trusted base images</strong> and scan images regularly (`docker scan`).<br>4. <strong>Keep images up-to-date</strong> to patch vulnerabilities.</p><h3>💡 Key Takeaways</h3><ul><li>Dockerfiles define your <strong>image blueprint</strong>, but efficiency comes from optimizing layers and leveraging caching.</li><li>Multi-stage builds reduce <strong>image size</strong> and improve security by separating build and runtime dependencies.</li><li>Tools like <strong>`dive`</strong> help visualize<strong> layers and space usage</strong>.</li><li>Security should be considered from day one, not as an afterthought.</li></ul><p>With these practices, you can build <strong><em>lightweight, secure, and production-ready Docker images</em></strong>, ready to scale for modern applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f611fba8d735" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsecops-ai/docker-made-simple-part-2-dockerfiles-custom-images-and-best-practices-f611fba8d735">Docker Made Simple: Part 2 : Dockerfiles, Custom Images, and Best Practices</a> was originally published in <a href="https://medium.com/devsecops-ai">DevSecOps &amp; AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Mastering AI Code Agents: A Developer’s Guide to Smarter, Faster, Cleaner Software]]></title>
            <link>https://medium.com/devsecops-ai/mastering-ai-code-agents-a-developers-guide-to-smarter-faster-cleaner-software-045dfe86b6b3?source=rss-6af5de26af7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/045dfe86b6b3</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[codeagent]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Yassine Ramzi]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 21:07:48 GMT</pubDate>
            <atom:updated>2025-10-11T17:23:38.413Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: The Hype and the Reality</h3><p>AI code agents like <strong>Claude, DeepSeek, Windsurf, and Cursor</strong> are becoming the hottest tools in software engineering. With a few prompts, they can generate unit tests, boilerplate, or even full features in minutes.</p><p>But here’s the reality: <strong>AI accelerates both good and bad practices.</strong> If you don’t know how to guide it, you’ll end up with fragile, insecure, and unmaintainable code.</p><p>The shift we’re experiencing isn’t about replacing developers — it’s about <strong>redefining their role</strong>. Engineers must return to the fundamentals: <strong>TDD, Clean Code, SOLID, design patterns, and OWASP security practices.</strong></p><p>AI is fast, but without discipline, it will amplify chaos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*93bWCQTB1vAjrt0i" /></figure><h3>From “Tech Stack Expert” to “Principle Expert”</h3><p>For years, developers identified themselves by the frameworks or languages they used: <strong>Java expert, Angular specialist, React guru.</strong></p><p>But languages evolve. Frameworks fade. What remains are <strong>engineering principles</strong>.</p><p>In the AI era:</p><ul><li>Anyone can generate a React component with a single prompt.</li><li>Few can design a secure, maintainable, and scalable system around it.</li></ul><p>👉 That’s why <strong>engineers must shift from being technology-centric to principle-centric.</strong></p><h3>The New Workflow with AI Code Agents</h3><p>The AI-driven development process looks different from the old one. Let’s walk through it step by step.</p><h4>Step 1: Specification by the Product Owner</h4><p>The <strong>Product Owner</strong> describes the feature in business terms.</p><ul><li>Example: <strong><em>“As a user, I want to reset my password via email so I can regain access if I forget it.”</em></strong></li></ul><h4>Step 2: Feature Page by the Developer</h4><p>Instead of jumping into code, the <strong>Developer</strong> writes a <strong>Feature Page</strong>:</p><ul><li><strong>User stories and acceptance criteria</strong></li><li><strong>Edge cases</strong> (expired reset links, brute force attempts)</li><li><strong>Non-functional requirements</strong> (security, performance)</li></ul><p>Example entries in the feature page:</p><ul><li><strong><em>The reset link must expire after 15 minutes.</em></strong></li><li><strong><em>Requests must be rate-limited to 5 per hour per IP.</em></strong></li></ul><h3>Step 3: Validation by the Tech Lead</h3><p>The <strong>Tech Lead</strong> validates the feature page:</p><ul><li>Ensures <strong>SOLID and Clean Code principles</strong> can be applied.</li><li>Identifies <strong>design patterns</strong> (e.g., Strategy for email providers).</li><li>Reviews <strong>security risks</strong> against <strong>OWASP Top 10</strong>.</li></ul><p>This step ensures the developer has a solid foundation before coding or before involving the AI agent.</p><h4>Example: Using AI for the Password Reset Feature</h4><p>Now let’s see the process in action with an AI code agent.</p><h4>1. TDD First</h4><p>Prompt:<br><strong><em>“Generate unit and integration tests for the password reset feature. Cover success, failure, expired tokens, and brute force attempts.”</em></strong></p><p>The agent creates tests with full functional coverage.</p><h4>2. Implementation</h4><p>Prompt:<br>“<strong>Implement the password reset feature to satisfy these tests. Follow Clean Code and SOLID principles.</strong>”</p><p>The agent generates the code.</p><h4><strong>3. Engineer Review</strong></h4><p>The developer reviews AI output for quality issues:</p><ul><li>Reset handler doing too much → violates <strong>Single Responsibility Principle</strong>.</li><li>Tokens stored in plaintext → <strong>OWASP violation</strong>.</li><li>Nested loops in validation → <strong>performance issue</strong>.</li></ul><h4>4. Refactoring with AI</h4><p>Prompt:<br><strong><em>“Refactor this code to:</em></strong></p><p><strong><em>* Remove nested loops by using a hashmap lookup.<br>* Apply SRP by splitting token generation and email sending.<br>* Hash tokens before storage for OWASP compliance.”</em></strong></p><p>AI updates the code accordingly.</p><h4>5. Re-run Tests and Create PR</h4><ul><li>Tests pass, validating correctness.</li><li>Developer submits a <strong>clean, secure, and principle-compliant pull request.</strong></li></ul><h3>Why Fundamentals Matter More Than Ever</h3><p>This process highlights a paradox: <strong><em>AI doesn’t remove the need for fundamentals, it makes them more critical.</em></strong></p><ul><li>Without TDD knowledge, you can’t judge AI-generated tests.</li><li>Without Clean Code skills, you can’t spot when AI creates spaghetti code.</li><li>Without security awareness, you’ll ship vulnerabilities AI unknowingly introduced.</li></ul><p><strong><em>AI is like a super-powered junior engineer</em></strong>: incredibly fast, but it needs careful supervision.</p><h3>Back to the Originals: TDD, Clean Code, Design Patterns</h3><p>The AI era forces engineers back to the classics:</p><ul><li><strong>TDD (Test-Driven Development):</strong> Write tests before implementation.</li><li><strong>Clean Code:</strong> Code must be readable and maintainable by humans.</li><li><strong>SOLID Principles: </strong>Guarantee modular, scalable architectures.</li><li><strong>Design Patterns:</strong> Proven solutions to recurring problems.</li><li><strong>OWASP Top 10:</strong> Security must be non-negotiable.</li></ul><p>These aren’t “nice to haves” they’re survival skills.</p><h3>Conclusion: The AI-Engineer Synergy</h3><p>The future is not AI replacing engineers. It’s AI <strong>augmenting</strong> engineers who master the craft.</p><ul><li><strong>Developers</strong>: Write feature pages, guide AI with tests, review code against principles.</li><li><strong>Tech Leads:</strong> Validate specs, enforce architecture, secure the system.</li><li><strong>AI Agents:</strong> Generate and refactor code at incredible speed.</li></ul><p>This new paradigm isn’t about forgetting fundamentals. It’s about making them <strong>the foundation of every AI-driven workflow.</strong></p><p>👉 The winners in this new era won’t be those who prompt the fastest, but those who <strong>understand software engineering deeply enough to guide AI output.</strong></p><p>💡 If you’re a developer today, stop obsessing over the latest framework. Start mastering the <strong>original : TDD</strong>, <strong>Clean Code</strong>, <strong>SOLID</strong>, and <strong>OWASP</strong>. They’re the compass that will keep you in control of AI-driven development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=045dfe86b6b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsecops-ai/mastering-ai-code-agents-a-developers-guide-to-smarter-faster-cleaner-software-045dfe86b6b3">🚀 Mastering AI Code Agents: A Developer’s Guide to Smarter, Faster, Cleaner Software</a> was originally published in <a href="https://medium.com/devsecops-ai">DevSecOps &amp; AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finally Understand Kafka: A Visual Guide with Real System Design Examples]]></title>
            <link>https://medium.com/h7w/finally-understand-kafka-a-visual-guide-with-real-system-design-examples-b8338eac6536?source=rss-6af5de26af7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8338eac6536</guid>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Yassine Ramzi]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 12:20:19 GMT</pubDate>
            <atom:updated>2025-09-09T22:44:38.497Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: Why Kafka Matters</h3><p>Every modern tech company relies on <strong>Apache Kafka</strong>. But for many developers, Kafka feels like a jungle of buzzwords: <strong>brokers, partitions, replication, offsets, consumer groups, DLQs</strong>.</p><p>In this guide, we’ll <strong>demystify Kafka</strong> with:</p><ul><li><strong>Concrete system design diagrams</strong></li><li><strong>Real production use cases</strong> (e-commerce)</li><li><strong>Step-by-step examples</strong> of brokers, partitions, and consumer groups</li></ul><p>By the end, you’ll see <strong>exactly how Kafka works in the real world</strong>, not just theory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GfaJ-E-3AGpO9HfL" /></figure><h3>1. Kafka Core Concepts (with Simple Definitions)</h3><h4>🔹 Broker</h4><p>A Kafka <strong>server</strong> that stores and serves data.</p><ul><li>A cluster = multiple brokers.</li><li><strong>Example</strong>: Broker 1 stores partitions of the `orders` topic.</li></ul><h4>🔹 Topic</h4><p>A <strong>named stream of messages</strong>.</p><ul><li><strong>Example:</strong> `orders`, `payments`, `notifications`.</li></ul><h4><strong>🔹 Partition</strong></h4><p>A topic is split into <strong>partitions</strong> for scalability.</p><ul><li>Each partition is an <strong>ordered log</strong>.</li><li><strong>Example:</strong> `orders` has 6 partitions → allows 6 consumers to read in parallel.</li></ul><h4>🔹 Replication</h4><p>Each partition is copied across brokers.</p><ul><li><strong>Example:</strong> `orders` <strong>Partition 0 <em>leader</em></strong> on <strong>Broker 1</strong>, replicas on <strong>Broker 2</strong> and <strong>Broker 3</strong>.</li><li>If Broker 1 crashes → Broker 2 becomes leader.</li></ul><h4>🔹 Offset</h4><p>A message’s <strong>position</strong> in a partition.</p><ul><li>Consumers track offsets <strong>per group</strong>.</li></ul><h4>🔹 Consumer Group</h4><p>A group of consumers reading a topic <strong>together</strong>.</p><ul><li>Each partition → consumed by only <strong>one consumer in the group</strong>.</li><li>Different groups can consume the same topic <strong>independently</strong>.</li></ul><h3>2. Real Production Example: E-Commerce Orders</h3><p>Imagine we’re building <strong>Amazon-like checkout flow</strong>.</p><h4>Setup</h4><ul><li>Topic: `orders` (6 partitions, replication factor = 3)</li><li>Brokers: 3 (B1, B2, B3)</li><li>Consumer Groups:</li><li><strong>`order-processors`</strong> (charge credit cards)</li><li><strong>`order-notifiers`</strong> (send emails/SMS)</li><li><strong>`order-analytics`</strong> (update dashboards)</li></ul><h4>Flow</h4><p>1. Customer places an order → Producer sends message to <strong>`orders`</strong>.<br>2. Kafka assigns it to Partition 0 (leader on Broker 1).<br>3. <strong>`order-processors`</strong> group → Consumer A processes it.<br>4. <strong>`order-notifiers`</strong> group → Consumer X also reads <strong>same message</strong> and sends email.<br>5. <strong>`order-analytics`</strong> → Consumer Y updates dashboard.</p><p>👉 One topic → multiple independent consumer groups → multiple business functions.</p><h3>3. Handling Failures with DLQ (Dead Letter Queue)</h3><p>In production, some messages fail. Example:</p><ul><li>Order message missing `customer_id`.</li><li>JSON parsing error.</li></ul><h4>DLQ Flow</h4><p>1. <strong>`order-processors`</strong> consumer fails to process message.<br>2. Instead of retrying forever → sends to <strong>`orders.DLQ`</strong>.<br>3. <strong>DLQ</strong> stores original payload + error reason.<br>4. A <strong>retry service or data team</strong> inspects and reprocesses later.</p><p>👉 DLQ ensures <strong>bad data doesn’t block good data</strong>.</p><h3>4. System Design Diagram (Kafka in Production)</h3><p><strong><em>Producers → Kafka Cluster (Brokers + Partitions + Replication) → Multiple Consumer Groups (Processing, Notifications, Analytics, DLQ).</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*X-Y-5Pgt16HW_18lReY9dA.png" /></figure><h3>5. Scaling Kafka in Production</h3><ul><li><strong>More partitions → more parallelism </strong>(but too many = overhead).</li><li><strong>Replication factor 3 </strong>= good HA (high availability).</li></ul><p><strong>Consumer scaling</strong>:</p><ul><li>1 partition → 1 consumer in group max.</li><li>If consumers &gt; partitions → some stay idle.</li><li><strong>Retention</strong>: Kafka can store messages for hours, days, or forever.</li></ul><h3>6. Mental Models &amp; Analogies</h3><ul><li><strong>Topic = Library section</strong> (Orders shelf)</li><li><strong>Partition = Bookshelf</strong> (ordered books)</li><li><strong>Message = Book</strong></li><li><strong>Offset = Page number</strong></li><li><strong>Consumer Group = Reading club</strong> (each club reads independently)</li><li><strong>DLQ = Broken books box</strong> (quarantine for errors)</li></ul><h3>7. Conclusion &amp; Takeaways</h3><p>Kafka is the <strong>backbone of event-driven architecture</strong>:</p><ul><li>Scales horizontally with partitions.</li><li>Survives failures with replication.</li><li>Supports multiple independent consumers via groups.</li><li>Handles errors gracefully with DLQ.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8338eac6536" width="1" height="1" alt=""><hr><p><a href="https://medium.com/h7w/finally-understand-kafka-a-visual-guide-with-real-system-design-examples-b8338eac6536">Finally Understand Kafka: A Visual Guide with Real System Design Examples</a> was originally published in <a href="https://medium.com/h7w">T3chtsz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Designing an AI-Powered Logistics Matching System: From ML Pipelines to Logging & Observability]]></title>
            <link>https://medium.com/devsecops-ai/%EF%B8%8F-designing-an-ai-powered-logistics-matching-system-from-ml-pipelines-to-logging-observability-f77d6b1d6256?source=rss-6af5de26af7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f77d6b1d6256</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ontology]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[logistics]]></category>
            <dc:creator><![CDATA[Yassine Ramzi]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 19:22:21 GMT</pubDate>
            <atom:updated>2025-09-09T07:21:46.324Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In logistics, the right carrier for the right shipment at the right time can mean the difference between profit and loss. Traditional systems rely on static rules, but with <strong>AI and ML</strong>, we can dynamically match shipments to carriers, optimize routes, and monitor decisions in real time.</blockquote><blockquote>Here’s how to design such a system end-to-end, including <strong>ML pipeline steps </strong>and <strong>observability</strong> for production reliability.</blockquote><h3>1️⃣ Problem Statement</h3><p>We want to build a logistics engine where:</p><ul><li>Clients post <strong>shipping orders</strong> (origin, destination, weight, deadline).</li><li>Logistics companies upload <strong>carrier/vehicle capacity &amp; availability</strong>.</li><li>The system automatically <strong>matches shipments to carriers</strong> using machine learning.</li></ul><p><strong>Challenges:</strong></p><ul><li>Text + numeric preprocessing.</li><li>Ontology-driven classification (cargo type, vehicle type, constraints).</li><li>Real-time matching and optimization.</li><li>Observability and auditability of every decision.</li></ul><h3>2️⃣ High-Level Architecture</h3><h4>Diagram Snapshot (System Design Sketch):</h4><pre>[Shipping Orders] ──▶ [Preprocessing + Embedding]<br>[Carrier Data] ──▶ [Preprocessing + Embedding]<br>           │<br>           ▼<br> [Ontology Classification]<br>           │<br>           ▼<br> [Matching Engine + Optimizer]<br>           │<br>           ▼<br> [Results + Logs (ELK)]</pre><h3>3️⃣ ML Pipeline Steps</h3><h4>a) Preprocessing</h4><ul><li><strong>Orders:</strong> tokenize location, weight, cargo description.</li><li><strong>Carriers: </strong>normalize capacity, route coverage, vehicle specs.</li><li><strong>Example: </strong>“Truck, refrigerated, 10 tons, Casablanca → Paris” → structured features.</li></ul><h4>b) Embeddings</h4><ul><li>Combine <strong>textual (cargo type)</strong> and <strong>numeric (capacity, distance, cost)</strong> into vectors.</li><li>Embeddings allow similarity scoring between orders and carriers.</li></ul><h4>c) Ontology Classification</h4><p>Ontology maps logistics knowledge:</p><ul><li><strong>Cargo Types:</strong> refrigerated, fragile, hazardous, bulk.</li><li><strong>Vehicle Types:</strong> truck, reefer, container ship, air cargo.</li><li><strong>Constraints:</strong> delivery deadlines, customs, weight restrictions.</li><li>Helps cluster and filter before detailed matching.</li></ul><h4>d) Matching Engine</h4><ul><li>Compute similarity (cosine distance + numeric constraints).</li><li>Optimize globally (e.g., minimize empty mileage, maximize load utilization).</li><li>Output: Best carrier(s) ranked per order.</li></ul><h3>4️⃣ Logging as a First-Class Citizen</h3><h4>Why Logs Matter in Logistics</h4><ul><li><strong>Explainability:</strong> Why was Carrier A chosen over Carrier B?</li><li><strong>Auditability:</strong> For compliance (customs, SLAs).</li><li><strong>Monitoring: </strong>Detect issues (capacity mismatch, delivery delays).</li></ul><h3>5️⃣ References in Logs</h3><p>Logs need <strong>IDs to stitch decisions together</strong>:</p><ul><li><strong>Order ID (order\_id):</strong> shipment reference.</li><li><strong>Carrier ID (carrier\_id):</strong> vehicle/company reference.</li><li><strong>Correlation ID (req\_id):</strong> trace full matching process for one request.</li><li><strong>Batch ID:</strong> track daily/weekly optimization runs.</li></ul><h3>6️⃣ Example Log Entry</h3><pre>{<br> &quot;timestamp&quot;: &quot;2025–09–08T10:32:45Z&quot;,<br> &quot;level&quot;: &quot;INFO&quot;,<br> &quot;order_id&quot;: &quot;ORD789&quot;,<br> &quot;carrier_id&quot;: &quot;CAR123&quot;,<br> &quot;correlation_id&quot;: &quot;REQ-logi001&quot;,<br> &quot;step&quot;: &quot;matching_engine&quot;,<br> &quot;similarity_score&quot;: 0.91,<br> &quot;ontology_matches&quot;: {&quot;cargo_type&quot;:&quot;refrigerated&quot;,&quot;vehicle&quot;:&quot;reefer_truck&quot;},<br> &quot;constraint_check&quot;: {&quot;capacity_ok&quot;:true,&quot;deadline_ok&quot;:true}<br>}</pre><h3>7️⃣ ELK Integration</h3><ul><li><strong>Logstash:</strong> enrich logs with metadata (region, order priority).</li><li><strong>Elasticsearch:</strong> store structured logs.</li><li><strong>Kibana:</strong> visualize system performance.</li></ul><p><strong>Example Dashboard Snapshots:</strong></p><ul><li>Map view: orders vs assigned carriers by region.</li><li>Histogram: similarity scores distribution per day.</li><li>Trace view: filter by `order_id = ORD789` to see all decision steps.</li></ul><h3>8️⃣ Observability Patterns</h3><ul><li><strong>Traceability</strong>: Follow one order’s journey from request to carrier assignment.</li><li><strong>Debugging</strong>: Why was a reefer truck unavailable for perishable cargo?</li><li><strong>Performance Metrics:</strong> Average matching time, % of orders delivered late.</li><li><strong>Alerts:</strong> Raise alarms if similarity scores fall below threshold (bad matches).</li></ul><h3>9️⃣ End-to-End Flow Example</h3><ol><li>Client posts order `ORD789`: 10 tons fresh produce, Casablanca → Paris, 48h.</li><li>Carrier `CAR123` (reefer truck, available in Casablanca) uploaded capacity.</li><li>Preprocessing + embeddings → classify cargo as “refrigerated”.</li><li>Matching engine assigns Carrier `CAR123` with similarity score 0.91.</li><li>Logs (with `correlation_id = REQ-logi001`) stored in ELK.</li><li>Ops team visualizes in Kibana: “Top reefer capacity utilization this week = 87%”.</li></ol><p>👉 This way, the system is not just matching shipments, but also <strong>auditing itself in real time</strong>, giving both <strong>operational efficiency</strong> and <strong>strategic insights</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f77d6b1d6256" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsecops-ai/%EF%B8%8F-designing-an-ai-powered-logistics-matching-system-from-ml-pipelines-to-logging-observability-f77d6b1d6256">🏗️ Designing an AI-Powered Logistics Matching System: From ML Pipelines to Logging &amp; Observability</a> was originally published in <a href="https://medium.com/devsecops-ai">DevSecOps &amp; AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Docker Made Simple — Part 1: Getting Started Without the Overwhelm]]></title>
            <link>https://medium.com/devsecops-ai/docker-made-simple-part-1-getting-started-without-the-overwhelm-8079e07691a6?source=rss-6af5de26af7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8079e07691a6</guid>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Yassine Ramzi]]></dc:creator>
            <pubDate>Thu, 04 Sep 2025 10:45:52 GMT</pubDate>
            <atom:updated>2025-09-06T07:30:32.628Z</atom:updated>
            <content:encoded><![CDATA[<h3>🐳 Docker Made Simple — Part 1: Getting Started Without the Overwhelm</h3><p>Docker is one of those tools that everyone <em>talks about</em>, but when you first try it, it feels like a black box. Images, containers, layers, volumes, networks… 🤯</p><p>The truth? You don’t need to learn everything at once. With just a few simple commands, you can start using Docker today — and understand what’s happening under the hood.</p><h3>☕ Why Docker Matters</h3><p>Think of Docker as a <strong>box for your app</strong>. Inside that box, you put:</p><ul><li>Your code</li><li>The runtime (Java, Node.js, Python, etc.)</li><li>The OS libraries it needs</li></ul><p>That box runs the <strong>same way everywhere</strong> — on your laptop, on your teammate’s machine, or on a production server.</p><p>No more: <em>“It works on my machine but not on production.”</em></p><h3>⚡ Installing Docker (The Right Way)</h3><ul><li><strong>Windows &amp; Mac</strong> → Install <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop</a></li><li><strong>Linux</strong> → Use your package manager (apt, dnf, etc.)</li></ul><p>Verify installation:</p><pre>docker --version</pre><h3>🐳 Your First Container (in 10 Seconds)</h3><p>Run this:</p><pre>docker run hello-world</pre><p>This does three things:</p><ol><li>Downloads the hello-world <strong>image</strong> (if it’s not cached locally).</li><li>Starts a <strong>container</strong> from that image.</li><li>Runs and exits after printing a message.</li></ol><p>👉 <strong>Image = recipe, Container = dish cooked from that recipe.</strong></p><h3>🔥 Run a Real Web Server: Nginx</h3><pre>docker run -d -p 8080:80 nginx</pre><ul><li>-d → run in background</li><li>-p 8080:80 → map your port 8080 → container port 80</li><li>nginx → the image name</li></ul><p>Now open <a href="http://localhost:8080/">http://localhost:8080</a> and you’ll see Nginx serving a welcome page. 🎉</p><h3>🐍 Run Python Without Installing Python</h3><p>No Python on your machine? No problem:</p><pre>docker run -it python:3.12 python</pre><p>This starts a Python REPL inside the container. You can play with Python 3.12 without touching your system install.</p><p>Exit with Ctrl+D.</p><h3>📦 Inside an Image: Layers</h3><p>A Docker <strong>image</strong> is not one big file. It’s built from <strong>layers</strong>:</p><ul><li>Each instruction in a Dockerfile creates a new layer (FROM, RUN, COPY).</li><li>Layers are <strong>cached and reused</strong>.</li><li>When you pull an image, Docker downloads only the missing layers.</li></ul><h3>🖼️ Example Dockerfile</h3><pre>FROM ubuntu:22.04            # Base layer (OS)<br>RUN apt-get update           # Layer for apt update<br>RUN apt-get install -y curl  # Layer with curl installed<br>COPY app.jar /app.jar        # Layer for your app code</pre><p>If you change only your app code (COPY), Docker reuses all previous layers.</p><h3>📊 Visual: Layers in an Image</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*gLdGAkNn8EGfDCKV7gWk4g.png" /></figure><p>👉 Each block is a layer. Docker caches them, so the next build is lightning fast.</p><p>Run this to see the actual layers of an image:</p><pre>docker history nginx</pre><h3>🔄 Image vs Container</h3><p>Many beginners mix these two up. Here’s the clear difference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*XITfzhsMLW75VltsCFTpHQ.png" /></figure><p><strong>Example:</strong> nginx image Example: a web server running on port 8080</p><p>👉 <strong>Key takeaway</strong>: An <strong>image</strong> never changes. A <strong>container</strong> is an image + a thin write layer for runtime changes.</p><h3>🧹 Cleaning Up</h3><p>List running containers:</p><pre>docker ps</pre><p>Stop a container:</p><pre>docker stop &lt;container_id&gt;</pre><p>Remove it:</p><pre>docker rm &lt;container_id&gt;</pre><p>List images:</p><pre>docker images</pre><p>Remove an image:</p><pre>docker rmi nginx</pre><h3>🎯 Mini-Challenge: Try It Yourself</h3><ol><li>Run a Redis container:</li></ol><pre>docker run -d -p 6379:6379 redis</pre><p>2. Check that it’s running:</p><pre>docker ps</pre><p>3. Connect with the Redis CLI:</p><pre>docker exec -it &lt;container_id&gt; redis-cli</pre><p>4. Run:</p><pre>SET hello world<br>GET hello</pre><p>👉 You just launched a database in seconds without installing Redis locally!</p><h3>🚀 What’s Next?</h3><p>In this first step, you learned how to:<br> ✅ Run your first containers<br> ✅ Serve apps instantly (Nginx, Python, Redis)<br> ✅ Understand how <strong>images are built from layers</strong><br> ✅ Differentiate <strong>images vs containers</strong> (with the write layer explained)</p><p>In <strong>Part 2</strong>, we’ll dive deeper into <strong>Dockerfiles and Custom Images</strong> — building your own image from scratch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8079e07691a6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsecops-ai/docker-made-simple-part-1-getting-started-without-the-overwhelm-8079e07691a6">🐳 Docker Made Simple — Part 1: Getting Started Without the Overwhelm</a> was originally published in <a href="https://medium.com/devsecops-ai">DevSecOps &amp; AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Why Java 21 Is a Game Changer for Your Everyday Development (+ Hands-On Example Github…]]></title>
            <link>https://medium.com/h7w/why-java-21-is-a-game-changer-for-your-everyday-development-hands-on-example-github-b56a1b287eba?source=rss-6af5de26af7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b56a1b287eba</guid>
            <category><![CDATA[pattern-matching]]></category>
            <category><![CDATA[virtual-threads]]></category>
            <category><![CDATA[java21]]></category>
            <category><![CDATA[bootcamp]]></category>
            <category><![CDATA[github-codespaces]]></category>
            <dc:creator><![CDATA[Yassine Ramzi]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 14:32:44 GMT</pubDate>
            <atom:updated>2025-09-02T18:31:24.420Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 Why Java 21 Is a Game Changer for Your Everyday Development (+ Hands-On Example Github CodeSpace)</h3><blockquote>&gt; <em>Ready to get your hands dirty? Skip to the [live Codespace on GitHub](</em><a href="https://github.com/yassineramzi/Java-21-OCA-boot-camp/tree/main/4-%20Loops">https://github.com/yassineramzi/Java-21-OCA-boot-camp/</a>)<em> and try Java 21 features now!</em></blockquote><h4>☕ The Java Evolution Continues</h4><p>Java has come a long way since its early days. Each new release adds just enough to stay modern, but Java 21? It’s different. It’s powerful, elegant, and finally feels like it’s <strong>built for developers in 2025</strong>. Whether you’re building microservices, backend APIs, or robust enterprise systems, Java 21 brings tangible improvements you’ll feel in your everyday workflow.</p><p>Let’s break down how Java 21 <strong>boosts performance</strong>, <strong>streamlines syntax</strong>, and how you can <strong>start using it today</strong> with hands-on examples.</p><h4>🔍 Day-to-Day Use — Where Java 21 Shines</h4><p>Here are the key features developers are actually using *right now*:</p><h4>1. ✅ <strong>Record Patterns</strong> and <strong>Pattern Matching for `switch`</strong> (Finalized)</h4><p>No more tedious `<strong>instanceof</strong>` checks or unsafe casting. Java 21 lets you write concise, readable logic for extracting data from objects.</p><pre><br>record Person(String name, int age) {}<br>void print(Person p) {<br> switch (p) {<br>   case Person(String name, int age) -&gt; System.out.println(name + &quot; is &quot; + age);<br> }<br>}</pre><blockquote>💡<strong>Real-life usage</strong>: Parsing DTOs, event-driven systems, API payloads.</blockquote><h4>2. 🧵 Virtual Threads (Finalized)</h4><p>Java 21’s Virtual Threads (from Project Loom) change the game in concurrency. Instead of 100 threads, you can spin up <strong>100,000 virtual threads</strong> — lightweight and super efficient.</p><pre><br>try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {<br> IntStream.range(0, 1000).forEach(i -&gt;<br>   executor.submit(() -&gt; System.out.println(&quot;Task &quot; + i))<br> );<br>}</pre><blockquote>🧠 <strong>Real-life usage:</strong> Reactive-like performance with imperative code — think APIs, scrapers, batch jobs.</blockquote><h4>3. 🧪 Scoped Values (Preview)</h4><p>Scoped values provide a safe and efficient alternative to thread-local variables, especially useful with virtual threads.</p><pre>ScopedValue&lt;String&gt; USER = ScopedValue.newInstance();<br>ScopedValue.where(USER, &quot;John&quot;).run(() -&gt; {<br> System.out.println(&quot;Current User: &quot; + USER.get());<br>});</pre><blockquote>🔒 <strong>Real-life usage</strong>: Passing contextual data (like request IDs) across thread boundaries in high-concurrency apps.</blockquote><h4>⚡ Performance: Java 21 vs Previous Versions</h4><p>The adoption of <strong>virtual threads</strong>, combined with i<strong>mprovements to the JIT compiler</strong>, and <strong>optimizations to pattern matching</strong> have shown:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*p_YoNJXtht63MEzmFox7QQ.png" /><figcaption>Comparaison between API Throughput(req/sec)</figcaption></figure><blockquote>&gt; 📈 Benchmarks from a typical REST API under load using JMH + Virtual Threads.</blockquote><blockquote>In short? <strong>Java 21 is the version where high-throughput, scalable concurrency becomes effortless.</strong></blockquote><h4>💻 Try Java 21 — Hands-On Playground</h4><p>I’ve created a <strong>ready-to-run GitHub Codespace</strong> so you can try Java 21 features instantly. Whether you want to explore Virtual Threads, pattern matching, or scoped values — it’s all there.</p><p>👉 [Open Java 21 Playground on GitHub](<a href="https://github.com/yassineramzi/Java-21-OCA-boot-camp">https://github.com/yassineramzi/Java-21-OCA-boot-camp</a>)</p><h4>1- Open codespace:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r86A6s3sijlbOwHrye96EQ.png" /></figure><h4>2- Run the code on your online Codespace :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkAdOeb3awatQYl1yt-s2Q.png" /></figure><h4>3- Execute the code :</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YG-SQYyr7CDhXYTz9krdnw.png" /></figure><p>No setup required. Just open, code, run.</p><h4>Final Thought</h4><p>Java 21 is not just another LTS — it’s the beginning of a <strong>new paradigm </strong>in how we write and run Java code. Cleaner syntax, better concurrency, and real productivity gains.</p><p>Now go ahead, try it live 👉 <strong>[GitHub Codespace]</strong>(<a href="https://github.com/yassineramzi/Java-21-OCA-boot-camp">https://github.com/yassineramzi/Java-21-OCA-boot-camp</a>) <br>And let me know what you build! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b56a1b287eba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/h7w/why-java-21-is-a-game-changer-for-your-everyday-development-hands-on-example-github-b56a1b287eba">🚀 Why Java 21 Is a Game Changer for Your Everyday Development (+ Hands-On Example Github…</a> was originally published in <a href="https://medium.com/h7w">T3chtsz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Subscription Reminder System in SaaS with Java 21 and Kafka]]></title>
            <link>https://medium.com/h7w/building-a-subscription-reminder-system-in-saas-with-java-21-and-kafka-0ec9d1ae11cf?source=rss-6af5de26af7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ec9d1ae11cf</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[monthly-recurring-revenue]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Yassine Ramzi]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 11:12:20 GMT</pubDate>
            <atom:updated>2025-09-01T20:29:54.133Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In SaaS products, <strong>reminders are revenue savers</strong>. When a client forgets to renew their subscription, you risk losing them — not because they dislike your service, but simply because they forgot. A smart reminder system ensures that clients are nudged at the right time, through the right channel, with the right message.</blockquote><blockquote>In this article, we’ll walk through designing and implementing a <strong>subscription reminder system</strong> in a microservices architecture, powered by <strong>Java 21, Spring Boot, Kafka, and a pluggable channel strategy (WhatsApp, SMS, Email, …)</strong>.</blockquote><h3>Problem Definition</h3><p>We need a system that:</p><ol><li>Tracks subscription start and end dates.</li><li>Automatically generates reminders (before and after expiry).</li><li>Sends reminders via user-preferred channels (WhatsApp, SMS, Email).</li><li>Uses templates defined by the provider.</li><li>Scales easily for millions of users without bottlenecks.</li></ol><h3>High-Level Architecture</h3><p>The architecture has several moving parts:</p><ul><li><strong>API Gateway</strong>: Entry point for clients and admin dashboards.</li><li><strong>Subscription Service</strong>: Manages subscriptions and calculates due dates.</li><li><strong>Reminder Scheduler (Cron Job)</strong>: Periodically computes upcoming reminders and stores them in a reminders table.</li><li><strong>Reminder Dispatcher</strong>: Picks reminders, sends them to <strong>Kafka</strong>, and updates their status.</li><li><strong>Kafka Bus</strong>: Decouples reminder generation from sending.</li><li><strong>Channel Microservices</strong>: Consumers for SMS, WhatsApp, Email, etc., each implementing its own delivery logic.</li></ul><p>Here’s a simplified diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*oLelFZYc46AQZsktCwO3VQ.png" /></figure><h3>Database Model</h3><p>We can use two tables:</p><h3>1- subscriptions</h3><pre>CREATE TABLE subscriptions (<br>    id BIGINT PRIMARY KEY,<br>    client_id BIGINT NOT NULL,<br>    start_date DATE NOT NULL,<br>    end_date DATE NOT NULL<br>);</pre><h3>2- reminders</h3><pre>CREATE TABLE reminders (<br>    id BIGINT PRIMARY KEY,<br>    subscription_id BIGINT NOT NULL,<br>    type VARCHAR(20) NOT NULL,       -- +3, -3, etc.<br>    channel VARCHAR(20) NOT NULL,    -- SMS, WHATSAPP, EMAIL<br>    template_id BIGINT NOT NULL,<br>    status VARCHAR(20) NOT NULL,     -- PENDING, SENT, FAILED<br>    scheduled_at TIMESTAMP NOT NULL<br>);</pre><h3>Java 21 Implementation</h3><p>We’ll use <strong>Spring Boot 3.x with Java 21</strong>.</p><h3>1. Reminder Entity</h3><pre>public record Reminder(<br>        Long id,<br>        Long subscriptionId,<br>        String type,      // e.g., +3 or -3<br>        String channel,   // SMS, WHATSAPP, EMAIL<br>        String templateId,<br>        String status,<br>        LocalDateTime scheduledAt<br>) {}</pre><h3>2. Scheduled Job to Compute Reminders</h3><pre>@Service<br>public class ReminderScheduler {<br><br>    private final ReminderRepository reminderRepository;<br><br>    private final ReminderDispatcher dispatcher;<br><br>    public ReminderScheduler(ReminderRepository reminderRepository,<br>                             ReminderDispatcher dispatcher) {<br>        this.reminderRepository = reminderRepository;<br>        this.dispatcher = dispatcher;<br>    }<br>    <br>    @Scheduled(cron = &quot;0 0 * * * *&quot;) // every hour<br>    public void computeAndDispatchReminders() {<br>        List&lt;Reminder&gt; dueReminders = reminderRepository.findByStatusAndScheduledNow(&quot;PENDING&quot;);<br>        dueReminders.forEach(reminder -&gt; {<br>            dispatcher.dispatch(reminder);<br>            reminder.status=&quot;DISPATCHED&quot;;           <br>            reminderRepository.save(reminder);<br>        });<br>    }<br>}</pre><h3>3. Reminder Dispatcher (Core Service)</h3><p>This is where we <strong>dispatch reminders to Kafka</strong>:</p><pre>@Service<br>public class ReminderDispatcher {<br>    private final KafkaTemplate&lt;String, Reminder&gt; kafkaTemplate;<br><br>    public ReminderDispatcher(KafkaTemplate&lt;String, Reminder&gt; kafkaTemplate) {<br>        this.kafkaTemplate = kafkaTemplate;<br>    }<br>    public void dispatch(Reminder reminder) {<br>        kafkaTemplate.send(&quot;reminders-topic&quot;, reminder);<br>        System.out.println(&quot;✅ Reminder &quot; + reminder.id() + &quot; dispatched to Kafka&quot;);<br>    }<br>}</pre><h3>4. Channel Strategy (Sealed Interface)</h3><pre>public sealed interface ChannelSender permits SmsSender, WhatsAppSender, EmailSender {<br>    void send(Reminder reminder);<br>}<br><br>public final class SmsSender implements ChannelSender {<br>    @Override<br>    public void send(Reminder reminder) {<br>        System.out.println(&quot;📱 Sending SMS for reminder &quot; + reminder.id());<br>    }<br>}<br><br>public final class WhatsAppSender implements ChannelSender {<br>    @Override<br>    public void send(Reminder reminder) {<br>        System.out.println(&quot;💬 Sending WhatsApp for reminder &quot; + reminder.id());<br>    }<br>}<br><br>public final class EmailSender implements ChannelSender {<br>    @Override<br>    public void send(Reminder reminder) {<br>        System.out.println(&quot;📧 Sending Email for reminder &quot; + reminder.id());<br>    }<br>}</pre><h3>5. Kafka Consumer for a Channel Service</h3><p>Example for SMS service:</p><pre>@Component<br>@KafkaListener(topics = &quot;reminders-topic&quot;, groupId = &quot;sms-service&quot;)<br>public class SmsReminderConsumer {<br>    private final SmsSender smsSender = new SmsSender();<br>    @KafkaHandler<br>    public void consume(Reminder reminder) {<br>        if (&quot;SMS&quot;.equalsIgnoreCase(reminder.channel())) {<br>            smsSender.send(reminder);<br>            System.out.println(&quot;✅ SMS sent for reminder &quot; + reminder.id());<br>        }<br>    }<br>}</pre><p>The same applies for WhatsApp and Email consumers.</p><h3>Why This Works</h3><ul><li><strong>Separation of concerns</strong>: Scheduler only computes due reminders, Dispatcher only dispatches, and Channels only send.</li><li><strong>Scalability</strong>: Kafka allows horizontal scaling per channel service.</li><li><strong>Open for extension Closed for modification </strong>: Adding a new channel is just a new ChannelSender and consumer.</li><li><strong>Resilience</strong>: Failures in SMS won’t block Email or WhatsApp.</li></ul><h3>Conclusion</h3><p>A SaaS reminder system is <strong>more than just sending an email</strong>. By designing around <strong>event-driven microservices with Kafka</strong>, you gain scalability, flexibility, and reliability. Users get timely, personalized notifications across their favorite channels, while your business secures predictable subscription renewals.</p><p>This architecture can serve as a <strong>blueprint</strong> for any SaaS startup serious about reducing churn and increasing customer retention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ec9d1ae11cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/h7w/building-a-subscription-reminder-system-in-saas-with-java-21-and-kafka-0ec9d1ae11cf">Building a Subscription Reminder System in SaaS with Java 21 and Kafka</a> was originally published in <a href="https://medium.com/h7w">T3chtsz</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI-Powered Code Reviewer with MCP — Part 2 (System Design & Implementation)]]></title>
            <link>https://medium.com/devsecops-ai/building-an-ai-powered-code-reviewer-with-mcp-part-2-system-design-implementation-752a020689fe?source=rss-6af5de26af7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/752a020689fe</guid>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[compliance]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[code-review]]></category>
            <dc:creator><![CDATA[Yassine Ramzi]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 15:10:08 GMT</pubDate>
            <atom:updated>2025-08-30T16:23:11.223Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an AI-Powered Code Reviewer with MCP — Part 2 (System Design &amp; Implementation)</h3><blockquote>In <a href="https://medium.com/@yassine.ramzi2010/building-an-ai-powered-code-reviewer-with-mcp-part-1-36f68906f900">[Part 1]</a>, we discussed the <strong>why </strong>and <strong>what</strong> of using the Model Context Protocol (MCP) to power AI-assisted code reviews. We explored challenges like GDPR compliance, intellectual property protection, and the need for workflows that respect enterprise policies.</blockquote><p>Now it’s time to shift from theory to practice.<br>In this article, we’ll cover:</p><ul><li>The <strong>system design</strong> of an MCP server.</li><li>A minimal yet clean <strong>MVP implementation</strong> in Python.</li><li>How to <strong>dockerize the server securely</strong> with multi-stage builds and a non-root execution model.</li></ul><p>This will give you a <strong>production-ready foundation</strong> you can extend with LLMs, rule engines, and observability.</p><h3>1. MCP Server System Design</h3><p>The MCP server is the **orchestration layer** that connects developers, AI models, and enterprise policies. It sits between:</p><h4>1.1. Clients (IDEs, tools, review bots)</h4><ul><li>Send requests (e.g., “review this file”).</li><li>Expect structured, actionable feedback.</li></ul><h4>1.2. AI Models (LLMs, rule engines, compliance validators)</h4><ul><li>Perform reasoning.</li><li>Return results in MCP’s standardized response format.</li></ul><h4>1.3. Compliance &amp; Security Filters</h4><ul><li>Apply GDPR/IP constraints.</li><li>Prevent data leakage or policy violations.</li></ul><h4>High-Level Flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbPbXh55fUZCu9FadN9RGw.png" /><figcaption>Review request flow</figcaption></figure><p>Every request is validated before reaching the AI, and every response is wrapped in a structured, predictable format.</p><h3>2. MVP Implementation (Clean Code First)</h3><p>Let’s build a <strong>minimal viable product (MVP)</strong> in Python.<br>This server won’t connect to a real LLM yet, but it will establish:</p><ul><li><strong>Separation of concerns</strong> (models, compliance, handlers).</li><li><strong>Policy enforcement </strong>before any review logic runs.</li><li><strong>Structured JSON responses</strong> following MCP style.</li></ul><h4>2.1. Project Layout</h4><p><strong>mcp-server/<br> ├─ app/<br> │ ├─ __init__.py<br> │ ├─ server.py<br> │ ├─ handlers.py<br> │ ├─ compliance.py<br> │ └─ models.py<br> ├─ requirements.txt<br> └─ Dockerfile</strong></p><p>This layout mirrors <strong>clean architecture principles</strong>:</p><ul><li>clear contracts (`models`),</li><li>business logic (`handlers`),</li><li>and cross-cutting concerns (`compliance`).</li></ul><h4>`requirements`</h4><pre>fastapi&gt;=0.95<br>uvicorn[standard]&gt;=0.22<br>pydantic&gt;=1.10<br>pytest&gt;=7.0<br>httpx&gt;=0.24</pre><h4>`models.py` — Data Contracts</h4><pre># app/models.py<br>from pydantic import BaseModel, Field<br>from typing import List, Optional<br><br>class CodeReviewRequest(BaseModel):<br>    repo: str = Field(..., description=&quot;Repository identifier, e.g., org/name&quot;)<br>    pr_id: Optional[int] = Field(None, description=&quot;Pull request id (optional)&quot;)<br>    author: Optional[str] = Field(None, description=&quot;Author username/email&quot;)<br>    file_path: str = Field(..., description=&quot;Path of the file being reviewed&quot;)<br>    code: str = Field(..., description=&quot;File contents or diff fragment&quot;)<br>    metadata: Optional[dict] = Field(default_factory=dict, description=&quot;Optional metadata&quot;)<br><br>class ReviewComment(BaseModel):<br>    line: int<br>    comment: str<br>    severity: str  # INFO, WARNING, ERROR<br><br>class CodeReviewResponse(BaseModel):<br>    repo: str<br>    pr_id: Optional[int]<br>    file_path: str<br>    comments: List[ReviewComment]<br>    sanitized: bool = False<br>    original_length: int = 0</pre><ul><li><strong>Pydantic</strong> enforces validation and serialization.</li><li>This ensures both input (requests) and output (responses) are type-safe and predictable.</li></ul><h4>`compliance.py` — Policy Layer</h4><pre># app/compliance.py<br>import re<br>from typing import Tuple<br><br># Patterns to detect typical secrets / tokens / emails (extend as needed)<br>EMAIL_RE = re.compile(r&quot;[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+&quot;)<br>LONG_HEX_RE = re.compile(r&quot;\b[0-9a-fA-F]{32,}\b&quot;)  # long hex tokens<br>AWS_KEY_RE = re.compile(r&quot;AKIA[0-9A-Z]{16}&quot;)  # AWS Access Key ID pattern (common example)<br>API_KEY_LIKE = re.compile(r&quot;(?i)(api[_-]?key|secret|token)[\s:=]+[&#39;\&quot;]?([A-Za-z0-9\-_\.]{16,})[&#39;\&quot;]?&quot;)<br><br>FORBIDDEN_KEYWORDS = {&quot;password&quot;, &quot;passwd&quot;, &quot;secret&quot;, &quot;api_key&quot;, &quot;private_key&quot;, &quot;confidential&quot;}<br><br><br>def _contains_forbidden_keyword(code: str) -&gt; bool:<br>    lower = code.lower()<br>    return any(word in lower for word in FORBIDDEN_KEYWORDS)<br><br><br>def sanitize_code(code: str) -&gt; Tuple[str, bool]:<br>    &quot;&quot;&quot;<br>    Sanitize code by redacting emails, long tokens, common API keys, and any discovered sensitive strings.<br>    Returns (sanitized_code, did_sanitize_bool)<br>    &quot;&quot;&quot;<br>    original = code<br>    sanitized = code<br><br>    # redact emails<br>    sanitized = EMAIL_RE.sub(&quot;[REDACTED_EMAIL]&quot;, sanitized)<br>    # redact long hex-like tokens<br>    sanitized = LONG_HEX_RE.sub(&quot;[REDACTED_TOKEN]&quot;, sanitized)<br>    # redact AWS-like keys<br>    sanitized = AWS_KEY_RE.sub(&quot;[REDACTED_AWS_KEY]&quot;, sanitized)<br><br>    # redact obvious api_key=... or token: ...<br>    def _api_key_repl(m):<br>        keyname = m.group(1)<br>        return f&quot;{keyname}= [REDACTED_SECRET]&quot;<br><br>    sanitized = API_KEY_LIKE.sub(_api_key_repl, sanitized)<br><br>    # naive line-based secret removal: remove lines containing forbidden keywords (redact value)<br>    def _redact_line(line: str) -&gt; str:<br>        low = line.lower()<br>        for kw in FORBIDDEN_KEYWORDS:<br>            if kw in low:<br>                # keep the key name, redact the rest of the line<br>                # simple heuristic: split at the keyword and redact after<br>                parts = re.split(f&quot;(?i)({kw})&quot;, line, maxsplit=1)<br>                if len(parts) &gt;= 3:<br>                    return parts[0] + parts[1] + &quot; [REDACTED]&quot;<br>                return &quot;[REDACTED_LINE]&quot;<br>        return line<br><br>    sanitized_lines = []<br>    for l in sanitized.splitlines():<br>        sanitized_lines.append(_redact_line(l))<br>    sanitized = &quot;\n&quot;.join(sanitized_lines)<br><br>    did_sanitize = sanitized != original<br>    return sanitized, did_sanitize<br><br><br>def validate_request(code: str) -&gt; Tuple[bool, str]:<br>    &quot;&quot;&quot;<br>    Validate the request according to simple policy rules.<br>    Returns (is_valid, reason)<br>    &quot;&quot;&quot;<br>    # If forbidden keywords present, reject<br>    if _contains_forbidden_keyword(code):<br>        return False, &quot;Request contains forbidden keywords that may indicate secrets.&quot;<br><br>    # If code is extremely large, reject (prevent DoS)<br>    if len(code) &gt; 1_000_000:  # 1MB cap for basic MVP<br>        return False, &quot;Payload too large.&quot;<br><br>    # Additional checks can be plugged here (PII detectors, allowlists, etc.)<br>    return True, &quot;OK&quot;</pre><p>This layer enforces <strong>organizational rules</strong> before code ever reaches an AI.</p><h4>`handlers.py` — Review Logic</h4><pre># app/handlers.py<br>from .models import CodeReviewRequest, CodeReviewResponse, ReviewComment<br>from .compliance import sanitize_code<br>from typing import List<br><br><br>class MCPTools:<br>    &quot;&quot;&quot;<br>    A small collection of typed tools the LLM/agent could call.<br>    In the real system these would be callable RPCs or structured tool calls.<br>    &quot;&quot;&quot;<br><br>    @staticmethod<br>    def analyze_diff_for_prints(code: str) -&gt; List[ReviewComment]:<br>        comments = []<br>        # naive: for each line that contains &#39;print(&#39; return a warning<br>        for idx, line in enumerate(code.splitlines(), start=1):<br>            if &quot;print(&quot; in line:<br>                comments.append(<br>                    ReviewComment(line=idx, comment=&quot;Avoid using &#39;print&#39; in production code.&quot;, severity=&quot;WARNING&quot;)<br>                )<br>        return comments<br><br>    @staticmethod<br>    def find_todos(code: str) -&gt; List[ReviewComment]:<br>        comments = []<br>        for idx, line in enumerate(code.splitlines(), start=1):<br>            if &quot;TODO&quot; in line or &quot;FIXME&quot; in line:<br>                comments.append(<br>                    ReviewComment(line=idx, comment=&quot;Resolve TODO/FIXME before merging.&quot;, severity=&quot;INFO&quot;)<br>                )<br>        return comments<br><br><br>def analyze_code(request: CodeReviewRequest) -&gt; CodeReviewResponse:<br>    &quot;&quot;&quot;<br>    Orchestrates available tools and returns an aggregated response.<br>    This function is intentionally simple to stay as an MVP. Replace<br>    or extend by calling an LLM agent that can call MCPTools methods.<br>    &quot;&quot;&quot;<br>    # sanitize code and remember if sanitized<br>    sanitized_code, sanitized_flag = sanitize_code(request.code)<br><br>    comments = []<br>    # call typed tools<br>    comments.extend(MCPTools.analyze_diff_for_prints(sanitized_code))<br>    comments.extend(MCPTools.find_todos(sanitized_code))<br><br>    # deduplicate comments on the same line with same message<br>    unique = {}<br>    for c in comments:<br>        key = (c.line, c.comment)<br>        if key not in unique:<br>            unique[key] = c<br>    deduped_comments = list(unique.values())<br><br>    response = CodeReviewResponse(<br>        repo=request.repo,<br>        pr_id=request.pr_id,<br>        file_path=request.file_path,<br>        comments=deduped_comments,<br>        sanitized=sanitized_flag,<br>        original_length=len(request.code)<br>    )<br>    return response</pre><p>Notice the <strong>plug-and-play design</strong>: today it’s static rules, tomorrow it could call GPT-5 or a custom linting engine.</p><h4>`server.py` — FastAPI Server</h4><pre># app/server.py<br>import logging<br>from fastapi import FastAPI, HTTPException, Request<br>from fastapi.responses import JSONResponse<br>from .models import CodeReviewRequest<br>from .compliance import validate_request<br>from .handlers import analyze_code<br><br>app = FastAPI(title=&quot;MCP Code Review Server&quot;, version=&quot;0.1.0&quot;)<br><br># configure basic logging<br>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(&quot;mcp.server&quot;)<br><br><br>@app.on_event(&quot;startup&quot;)<br>async def startup_event():<br>    logger.info(&quot;MCP Code Review Server starting up.&quot;)<br><br><br>@app.get(&quot;/health&quot;)<br>async def health():<br>    return {&quot;status&quot;: &quot;ok&quot;}<br><br><br>@app.post(&quot;/review&quot;)<br>async def review_code(request: CodeReviewRequest):<br>    logger.info(&quot;Received review request: repo=%s file=%s pr=%s&quot;, request.repo, request.file_path, request.pr_id)<br>    is_valid, reason = validate_request(request.code)<br>    if not is_valid:<br>        logger.warning(&quot;Rejected request: %s&quot;, reason)<br>        raise HTTPException(status_code=400, detail=reason)<br><br>    # Process<br>    response = analyze_code(request)<br>    logger.info(&quot;Review completed: comments=%d sanitized=%s&quot;, len(response.comments), response.sanitized)<br>    return JSONResponse(status_code=200, content=response.dict())<br><br><br>@app.exception_handler(Exception)<br>async def generic_exception_handler(request: Request, exc: Exception):<br>    logger.exception(&quot;Unhandled exception while handling request: %s&quot;, exc)<br>    return JSONResponse(status_code=500, content={&quot;detail&quot;: &quot;Internal server error&quot;})</pre><ul><li><strong>FastAPI</strong> provides automatic docs (`/docs`) for testing.</li><li>The `review` endpoint enforces compliance <strong>before</strong> analysis.</li></ul><h3>3. Dockerization (Secure by Default)</h3><p>We’ll now <strong>dockerize </strong>the server for production.<br>Key goals: small images, no root user, repeatable builds.</p><h4>Dockerfile</h4><pre># - - - - - Build Stage - - - - - <br>FROM python:3.11-slim AS builder<br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install - no-cache-dir -r requirements.txt<br># - - - - - Production Stage - - - - - <br>FROM python:3.11-slim<br># Create non-root user<br>RUN groupadd -r mcp &amp;&amp; useradd -r -g mcp mcpuser<br>WORKDIR /app<br>COPY - from=builder /usr/local /usr/local<br>COPY app/ ./app<br>USER mcpuser<br>EXPOSE 8000<br>CMD [&quot;uvicorn&quot;, &quot;app.server:app&quot;, &quot; - host&quot;, &quot;0.0.0.0&quot;, &quot; - port&quot;, &quot;8000&quot;]</pre><h4>Why this matters:</h4><ul><li><strong>Multi-stage build</strong> → slimmer final image.</li><li><strong>Non-root execution</strong> → reduces attack surface.</li><li><strong>Explicit WORKDIR and COPY</strong> → only what’s needed makes it into the container.</li></ul><h3>Test Example: S3Uploader.java</h3><p>To test the MCP server, we use the following **realistic Java snippet** that uploads a file to an S3 bucket:</p><pre>// File: S3Uploader.java<br>import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;<br>import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;<br>import software.amazon.awssdk.regions.Region;<br>import software.amazon.awssdk.services.s3.S3Client;<br>import software.amazon.awssdk.services.s3.model.PutObjectRequest;<br>import software.amazon.awssdk.services.s3.model.S3Exception;<br>import java.nio.file.Paths;<br><br>public class S3Uploader {<br><br>    public static void main(String[] args) {<br>        // TODO: Replace System.out.println with proper logging<br>        System.out.println(&quot;Starting S3 upload process...&quot;);<br><br>        String accessKey = &quot;AKIAEXAMPLEAWSKEY123456&quot;;<br>        String secretKey = &quot;wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY&quot;;<br><br>        AwsBasicCredentials awsCreds = AwsBasicCredentials.create(accessKey, secretKey);<br>        S3Client s3 = S3Client.builder()<br>                .region(Region.US_EAST_1)<br>                .credentialsProvider(StaticCredentialsProvider.create(awsCreds))<br>                .build();<br><br>        String bucketName = &quot;my-test-bucket&quot;;<br>        String keyName = &quot;example.txt&quot;;<br>        String filePath = &quot;/tmp/example.txt&quot;;<br><br>        try {<br>            PutObjectRequest putReq = PutObjectRequest.builder()<br>                    .bucket(bucketName)<br>                    .key(keyName)<br>                    .build();<br>            s3.putObject(putReq, Paths.get(filePath));<br>            System.out.println(&quot;Upload successful!&quot;);<br>        } catch (S3Exception e) {<br>            System.err.println(&quot;Failed to upload to S3: &quot; + e.awsErrorDetails().errorMessage());<br>        }<br>    }<br>}</pre><p><strong>Explanation of the code and potential issues:</strong></p><ol><li><strong>Hardcoded AWS credentials</strong></li></ol><p>The `accessKey` and `secretKey` are hardcoded in the source file. This is a major security flaw because sensitive credentials should never appear in source code.</p><p><strong><em>Our MCP server’s compliance layer can detect these patterns and flag them for remediation.</em></strong></p><p><strong>2. Use of `System.out.println` for logging</strong><br> The code uses `System.out.println` to log important operations. In production code, this is not recommended; a proper logging framework should be used.</p><p><strong><em>MCP will detect `print` statements (or their Java equivalents) and generate warnings.</em></strong></p><p><strong>3. TODO comment</strong><br> The `// TODO: Replace System.out.println with proper logging` comment signals unfinished code.</p><p><strong><em>MCP scans for TODO/FIXME comments and provides informational suggestions to the developer.</em></strong></p><p><strong>4. Error handling</strong><br> The `catch (S3Exception e)` block prints the error to standard error. While better than ignoring exceptions,</p><p><strong><em>MCP can recommend using structured logging, metrics, or retries.</em></strong></p><p><strong>How MCP analyzes this snippet:</strong></p><p>When the MCP server receives this file via the `<strong>/review</strong>` endpoint:</p><ul><li>The <strong>compliance layer </strong>scans for sensitive data (like AWS keys) and flags violations.</li><li>The <strong>analyze\_code</strong> handler identifies unsafe `System.out.println` calls and TODO comments.</li><li>A <strong>structured MCP response</strong> is returned, containing line numbers, severity levels, and actionable suggestions, e.g.:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-pTO4KSVjaWXzIBRkvFlQ.png" /></figure><h4>Example 1 :</h4><p><strong>Request :</strong></p><pre>{<br>  &quot;repo&quot;: &quot;org/sample&quot;,<br>  &quot;pr_id&quot;: 42,<br>  &quot;author&quot;: &quot;alice&quot;,<br>  &quot;file_path&quot;: &quot;src/S3Uploader.java&quot;,<br>  &quot;code&quot;: &quot;import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;\nimport software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;\nimport software.amazon.awssdk.regions.Region;\nimport software.amazon.awssdk.services.s3.S3Client;\nimport software.amazon.awssdk.services.s3.model.PutObjectRequest;\nimport software.amazon.awssdk.services.s3.model.S3Exception;\nimport java.nio.file.Paths;\n\npublic class S3Uploader {\n\n    public static void main(String[] args) {\n        // TODO: Replace System.out.println with proper logging\n        System.out.println(\&quot;Starting S3 upload process...\&quot;);\n\n        String accessKey = \&quot;AKIAEXAMPLEAWSKEY123456\&quot;;\n        String secretKey = \&quot;wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\&quot;;\n\n        AwsBasicCredentials awsCreds = AwsBasicCredentials.create(accessKey, secretKey);\n        S3Client s3 = S3Client.builder()\n                .region(Region.US_EAST_1)\n                .credentialsProvider(StaticCredentialsProvider.create(awsCreds))\n                .build();\n\n        String bucketName = \&quot;my-test-bucket\&quot;;\n        String keyName = \&quot;example.txt\&quot;;\n        String filePath = \&quot;/tmp/example.txt\&quot;;\n\n        try {\n            PutObjectRequest putReq = PutObjectRequest.builder()\n                    .bucket(bucketName)\n                    .key(keyName)\n                    .build();\n\n            s3.putObject(putReq, Paths.get(filePath));\n\n            System.out.println(\&quot;Upload successful!\&quot;);\n        } catch (S3Exception e) {\n            System.err.println(\&quot;Failed to upload to S3: \&quot; + e.awsErrorDetails().errorMessage());\n        }\n    }\n}&quot;<br>}</pre><p><strong>Response :</strong></p><pre>{<br>  &quot;detail&quot;: &quot;Request contains forbidden keywords that may indicate secrets.&quot;<br>}</pre><h4>Example 2 :</h4><p><strong>Request :</strong></p><pre>{<br>    &quot;repo&quot;: &quot;org/sample&quot;,<br>    &quot;pr_id&quot;: 7,<br>    &quot;author&quot;: &quot;bob&quot;,<br>    &quot;file_path&quot;: &quot;src/hello.py&quot;,<br>    &quot;code&quot;: &quot;def hello():\n    print(\&quot;hello world\&quot;)\n    # TODO: add tests\n    token = \&quot;AKIAEXAMPLEAWSKEY123456\&quot;\n    email = \&quot;bob@example.com\&quot;\n&quot;<br>  }</pre><p><strong>Response:</strong></p><pre>{<br>  &quot;repo&quot;: &quot;org/sample&quot;,<br>  &quot;pr_id&quot;: 7,<br>  &quot;file_path&quot;: &quot;src/hello.py&quot;,<br>  &quot;comments&quot;: [<br>    {<br>      &quot;line&quot;: 2,<br>      &quot;comment&quot;: &quot;Avoid using &#39;print&#39; in production code.&quot;,<br>      &quot;severity&quot;: &quot;WARNING&quot;<br>    },<br>    {<br>      &quot;line&quot;: 3,<br>      &quot;comment&quot;: &quot;Resolve TODO/FIXME before merging.&quot;,<br>      &quot;severity&quot;: &quot;INFO&quot;<br>    }<br>  ],<br>  &quot;sanitized&quot;: true,<br>  &quot;original_length&quot;: 128<br>}</pre><p>This demonstrates <strong>how MCP transforms a code snippet into actionable insights</strong>, enforcing compliance, improving code quality, and reducing security risks automatically.</p><h3>5. Next Steps</h3><p>This Part 2 MVP demonstrates:<br>✅ Clean modular design (models, handlers, compliance).<br>✅ Early policy enforcement for GDPR/IP compliance.<br>✅ Secure <strong>containerization</strong> with non-root builds.</p><p>In <strong>Part 3</strong>, we’ll extend this into a <strong>full-featured AI reviewer</strong> with:</p><ul><li>Integration with real <strong>LLMs</strong> (both local and external).</li><li><strong>Plugin architecture</strong> for custom rules (linting, security, coverage).</li><li><strong>Observability hooks</strong> for logging, metrics, and tracing.</li></ul><h3>🗂️ Full Source Code</h3><p>If you’d like to dive deeper or try the implementation yourself, the complete source code is available on GitHub:</p><p>👉 <a href="https://github.com/yassineramzi/code-review-mcp-server">code-review-mcp-server (master branch)</a></p><p>The repository contains the full MVP MCP server implementation, Docker setup, and examples you can run locally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=752a020689fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/devsecops-ai/building-an-ai-powered-code-reviewer-with-mcp-part-2-system-design-implementation-752a020689fe">Building an AI-Powered Code Reviewer with MCP — Part 2 (System Design &amp; Implementation)</a> was originally published in <a href="https://medium.com/devsecops-ai">DevSecOps &amp; AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>