<?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 Ayoub Taouam on Medium]]></title>
        <description><![CDATA[Stories by Ayoub Taouam on Medium]]></description>
        <link>https://medium.com/@ayoubtaouam?source=rss-8e17f7fd0be8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*grTiZ9MRTkAeo07M8e6NRg.png</url>
            <title>Stories by Ayoub Taouam on Medium</title>
            <link>https://medium.com/@ayoubtaouam?source=rss-8e17f7fd0be8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:49:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayoubtaouam/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[Advanced Spring Boot Configuration: @ConfiguratioProperties, YAML vs Properties and Relaxed Binding]]></title>
            <link>https://medium.com/@ayoubtaouam/advanced-spring-boot-configuration-configuratioproperties-yaml-vs-properties-and-relaxed-binding-504ac53b32e7?source=rss-8e17f7fd0be8------2</link>
            <guid isPermaLink="false">https://medium.com/p/504ac53b32e7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[yaml]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[configuration-properties]]></category>
            <category><![CDATA[spring-boot-configuration]]></category>
            <dc:creator><![CDATA[Ayoub Taouam]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 09:40:40 GMT</pubDate>
            <atom:updated>2026-02-18T09:40:40.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced Spring Boot Configuration: @ConfigurationProperties, YAML vs Properties and Relaxed Binding</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*olgHkhXR3x2qAdF9ITiATA.png" /></figure><p>Configuration is the silent backbone of every Spring Boot application.</p><p>Database URLs.</p><p>Security settings.</p><p>Feature toggles.</p><p>Timeout values.</p><p>External API keys.</p><p>When configuration is clean, your application feels elegant, when it’s messy your projects becomes fragile.</p><p>In this article, we’ll go beyond basic application.properties usage and explore:</p><ul><li>Why configuration design matters</li><li>How @ConfigurationProperties improves structure</li><li>YAML vs .properties, when and why to use each</li><li>What <strong>relaxed binding</strong> really means (and why it’s powerful)</li></ul><h3>Why Configuration Deserves Architectural Attention</h3><p>Many developers treat configuration like a side detail:</p><pre>app.timeout=5000<br>app.url=https://example.com<br>app.retry=3</pre><p>This works until you have 200+ configuration keys, where values get duplicated, validation becomes manual and environments behave inconsistently.</p><p>Configuration is not just “settings”. It is part of your system&#39;s design.</p><h3>@ConfigurationProperties: Structured Configuration the Right Way</h3><p>Let’s start with the most important tool.</p><h4>The Problem with @Value</h4><p>A common pattern:</p><pre>@Value(&quot;${app.timeout}&quot;)<br>private int timeout;</pre><p>This works, but:</p><ul><li>Scattered across the codebase</li><li>No grouping</li><li>No type safety guarantees</li><li>No built-in validation</li><li>Harder to maintain</li></ul><h4>@ConfigurationProperties</h4><p>@ConfigurationProperties allows you to bind configuration into a structured Java class.</p><p>Example Configuration</p><pre>app:<br>  client:<br>    url: https://api.example.com<br>    timeout: 5000<br>    retry: 3</pre><p>Java Class</p><pre>@ConfigurationProperties(prefix = &quot;app.client&quot;)<br>public class ClientProperties {<br><br>    private String url;<br>    private int timeout;<br>    private int retry;<br><br>    // getters and setters<br>}</pre><p>Then register it:</p><pre>@EnableConfigurationProperties(ClientProperties.class)</pre><p>Now your config is grouped logically, type-safe and centralized.</p><h4>This is Better</h4><p>Instead of injecting individual values:</p><pre>private final ClientProperties clientProperties;</pre><p>You now inject a <strong>configuration object</strong>.</p><p>This improves readability, maintainability and dependency clarity, this is configuration with structure.</p><h4>Adding Validation</h4><p>You can validate configuration automatically:</p><pre>@ConfigurationProperties(prefix = &quot;app.client&quot;)<br>@Validated<br>public class ClientProperties {<br><br>    @NotBlank<br>    private String url;<br><br>    @Min(1000)<br>    private int timeout;<br><br>    @Min(0)<br>    private int retry;<br>}</pre><p>If invalid configuration is provided, the application would <strong>fails</strong> at startup.</p><p>This is extremely valuable.</p><h3>YAML vs Properties: Which One Should You Use?</h3><p>Spring Boot supports both:</p><ul><li>application.properties</li><li>application.yml</li></ul><p>They do exactly the same thing, but their structure differs.</p><h4>Properties Format</h4><pre>app.client.url=https://api.example.com<br>app.client.timeout=5000<br>app.client.retry=3</pre><p>Flat and explicit</p><h4>YAML Format</h4><pre>app:<br>  client:<br>    url: https://api.example.com<br>    timeout: 5000<br>    retry: 3</pre><p>Hierarchical and cleaner for nested structures.</p><h4>When YAML Is Better</h4><p>YAML shine when:</p><ul><li>You have nested configuration</li><li>You use lists</li><li>You use complex objects</li></ul><p>Example with a list:</p><pre>app:<br>  servers:<br>    - host: server1<br>      port: 8080<br>    - host: server2<br>      port: 9090</pre><p>This is much cleaner.</p><h4>When Properties Might Be Better</h4><p>Properties are sometimes preferred when:</p><ul><li>You want simplicity</li><li>You have very flat config</li><li>You want to avoid YAML <strong>indentation errors</strong></li><li>Teams are more familiar with .properties</li></ul><p>There’s no universal winner.</p><h3>Relaxed Binding: Why Spring Feels So Flexible</h3><p>One of Spring Boot’s smartest features is <strong>relaxed binding</strong>.</p><p>.It means Spring can map configuration keys to Java fields in multiple naming styles.</p><h4>Example</h4><p>Given this Java field:</p><pre>private int connectionTimeout;</pre><p>Spring can bind all o these:</p><pre>connection-timeout=5000<br>connection_timeout=5000<br>connectionTimeout=5000<br>CONNECTION_TIMEOUT=5000</pre><p>Even environment variables:</p><pre>CONNECTION_TIMEOUT=5000</pre><p>All work.</p><h4>Why Relaxed Binding Matters</h4><p>This flexibility allows:</p><ul><li>clean YAML</li><li>Consistent Java naming</li><li>Seamless environment overrides</li></ul><p>It also removes friction between:</p><ul><li>Java naming conventions (camelCase)</li><li>Config naming conventions (kebab-case)</li><li>Environment variables (UPPER_SNAKE_CASE)</li></ul><p>This is one reason Spring Boot feels so “natural”.</p><h3>How All These Pieces Work Together</h3><p>Let’s combine everything:</p><p>application.yml</p><pre>app:<br>  mail:<br>    host: smtp.example.com<br>    port: 587<br>    username: user<br>    password: secret</pre><p>Properties Class</p><pre>@ConfigurationProperties(prefix = &quot;app.mail&quot;)<br>@Validated<br>public class MailProperties {<br><br>    @NotBlank<br>    private String host;<br><br>    private int port;<br><br>    private String username;<br>    private String password;<br><br>    // getters and setters<br>}</pre><p>Usage in a service</p><pre>@Service<br>public class MailService {<br><br>    private final MailProperties properties;<br><br>    public MailService(MailProperties properties) {<br>        this.properties = properties;<br>    }<br>}</pre><p>This is:</p><ul><li>Clean</li><li>Structured</li><li>Validated</li><li>Maintainable</li><li>Production-ready</li></ul><h3>Wrap Up</h3><p>Advances Spring Boot configuration is not about syntax.</p><p>It’s about:</p><ul><li>Structure</li><li>Safety</li><li>Maintainability</li><li>Clarity</li></ul><p>If your application is growing and you’re still relying hevily on @Value, it’s time to level up.</p><p>Move toward:</p><ul><li>Structured configuration classes</li><li>Validation at startup</li><li>Clean grouping by domain</li></ul><p>Configuration done right makes your system easier to evolve, and much harder to break.</p><p><em>Follow for more!!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=504ac53b32e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing API Versioning in Spring Boot: URI, Header and Media Type Strategies]]></title>
            <link>https://medium.com/@ayoubtaouam/implementing-api-versioning-in-spring-boot-uri-header-and-media-type-strategies-4138ec70cc21?source=rss-8e17f7fd0be8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4138ec70cc21</guid>
            <category><![CDATA[api-versioning]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[media-type]]></category>
            <category><![CDATA[http-headers]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Ayoub Taouam]]></dc:creator>
            <pubDate>Thu, 12 Feb 2026 15:46:50 GMT</pubDate>
            <atom:updated>2026-02-12T15:46:50.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fYpFxnF7diSMxnVm8KtDlQ.png" /></figure><p>APIs evolve.</p><p>You add fields.</p><p>You remove fields.</p><p>You change validation rules.</p><p>You rethink response structures.</p><p>And then one day, a client breaks.</p><p>That’s when you realize:</p><blockquote><em>An API is not just code, it’s a contract.</em></blockquote><p>API versioning exists to protect that contract while allowing your system to grow.</p><p>In this article, we’ll explore:</p><ul><li>Why API versioning matters</li><li>The three main strategies (URI, Header, Media Type)</li><li>How to implement each one in Spring Boot</li><li>When to choose which approach</li></ul><h3>Why API Versioning Is Necessary</h3><p>Imagine you have this endpoint:</p><pre>GET /users</pre><p>It returns:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;name&quot;: &quot;Alice&quot;<br>}</pre><p>Now you decide to improve your design:</p><pre>{<br>  &quot;id&quot;: 1,<br>  &quot;firstName&quot;: &quot;Alice&quot;,<br>  &quot;lastName&quot;: &quot;Smith&quot;<br>}</pre><p>Looks better, right?</p><p>But an existing mobile app excepts name.</p><p>It crashes.</p><p>Without versioning, every breaking change becomes a production risk.</p><p>Versioning allows you to:</p><ul><li>Keep old clients working</li><li>Introduce improvements safely</li><li>Evolve your API without fear</li></ul><h3>The Three Main Versioning Strategies</h3><p>There are three widely used strategies:</p><ul><li>URI Versioning</li><li>Header Versioning</li><li>Media Type (Content Negotiation) Versioning</li></ul><p>Each solves the same problem, but in different ways.</p><h3>URI Versioning</h3><h4>What It Looks Like</h4><pre>GET /api/v1/users<br>GET /api/v2/users</pre><p>The version is part of the URL.</p><h4>Spring Boot Implementation</h4><pre>@RestController<br>@RequestMapping(&quot;/api/v1/users&quot;)<br>public class UserControllerV1 {<br><br>    @GetMapping<br>    public List&lt;UserV1&gt; getUsers() {<br>        return List.of(new UserV1(&quot;Alice&quot;));<br>    }<br>}</pre><p>And for V2:</p><pre>@RestController<br>@RequestMapping(&quot;/api/v1/users&quot;)<br>public class UserControllerV1 {<br><br>    @GetMapping<br>    public List&lt;UserV1&gt; getUsers() {<br>        return List.of(new UserV1(&quot;Alice&quot;));<br>    }<br>}</pre><p>Simple, clear, explicit.</p><h4>Pros:</h4><ul><li>Easy to understand</li><li>Easy to test</li><li>Easy to document</li><li>Visible in browser and logs</li></ul><h4>Cons:</h4><ul><li>URL changes for each version</li><li>Some consider it less “RESTful”</li><li>Can duplicate controller logic</li></ul><h3>Header Versioning</h3><p>Instead of changing the URL, you send the version in a header:</p><pre>GET /api/users<br>X-API-VERSION: 1</pre><p>The URI stays clean.</p><h4>Spring Boot Implementation</h4><pre>@GetMapping(value = &quot;/users&quot;, headers = &quot;X-API-VERSION=1&quot;)<br>public List&lt;UserV1&gt; getUsersV1() {<br>    return List.of(new UserV1(&quot;Alice&quot;));<br>}</pre><pre>@GetMapping(value = &quot;/users&quot;, headers = &quot;X-API-VERSION=2&quot;)<br>public List&lt;UserV2&gt; getUsersV2() {<br>    return List.of(new UserV2(&quot;Alice&quot;, &quot;Smith&quot;));<br>}</pre><p>Spring automatically routes based on header conditions.</p><h4>Pros:</h4><ul><li>Cleaner URLs</li><li>Versioning becomes metadata</li><li>Keeps resource identity stable</li></ul><h4>Cons:</h4><ul><li>Harder to test manually in browser</li><li>Less visible in logs</li><li>Some API consumes forget to send headers</li></ul><p>Good for mature systems with controller clients.</p><h3>Media Type Versioning</h3><p>This is the most REST-aligned and most misunderstood approach.</p><p>The version is specific in the Accept header:</p><pre>Accept: application/vnd.company.app-v1+json</pre><p>Or:</p><pre>Accept: application/vnd.company.app-v2+json</pre><h4>Spring Boot Implementation</h4><pre>@GetMapping(value = &quot;/users&quot;, produces = &quot;application/vnd.company.app-v1+json&quot;)<br>public List&lt;UserV1&gt; getUsersV1() {<br>    return List.of(new UserV1(&quot;Alice&quot;));<br>}</pre><pre>@GetMapping(value = &quot;/users&quot;, produces = &quot;application/vnd.company.app-v2+json&quot;)<br>public List&lt;UserV2&gt; getUsersV2() {<br>    return List.of(new UserV2(&quot;Alice&quot;, &quot;Smith&quot;));<br>}</pre><p>Spring matches based on the Accept header.</p><h4>Pros:</h4><ul><li>The resource URI stays the same</li><li>Only the representation changes</li><li>Versioning is treated as content format negotiation</li></ul><p>This aligns closely with REST principles.</p><h4>Cons:</h4><ul><li>More complex</li><li>Harder to explain</li><li>Harder for frontend/mobile teams</li><li>Not always well-supported in API tools</li></ul><h3>Practical Advice</h3><p>For most internal or enterprise APIs:</p><blockquote><em>Use URI versioning.</em></blockquote><p>It is:</p><ul><li>Explicit</li><li>Clear</li><li>Easy to manage</li><li>Easy for frontend teams</li></ul><p>For public APIs with strict design goals:</p><blockquote><em>Consider header or media type versioning.</em></blockquote><p>But remember:</p><p>Clarity often beats theoretical purity.</p><h3>Versioning Best Practices</h3><p>Versioning is not just about the URL or header.</p><p>You should:</p><h4>1. Version Only When You Break Compatibility</h4><p>Adding optional fields usually doesn’t require a new version.</p><p>Removing or naming fields does.</p><h4>2. Don’t Over-Version</h4><p>Avoid:</p><pre>/v1.0.1<br>/v1.0.2</pre><p>Keep versions coarse-grained:</p><pre>v1<br>v2</pre><h4>3. Maintain Older Versions Thoughtfully</h4><ul><li>Deprecate properly</li><li>Announce timelines</li><li>Monitor usage</li><li>Remove Safely</li></ul><h3>Wrap Up</h3><p>Think of your API like a book, versioning is like publishing a new edition, you don’t rewrite the old edition in place or force readers to update immediately.</p><p>You publish a new edition, keep the old one available and eventually phase it out.</p><p>APIs deserve the same respect. Because at the end, an API is not just code.</p><p>It’s a promise.</p><p><em>Follow for more!!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4138ec70cc21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Records: Simplifying Immutable Data Classes]]></title>
            <link>https://medium.com/@ayoubtaouam/java-records-simplifying-immutable-data-classes-9c4745ea5dc8?source=rss-8e17f7fd0be8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c4745ea5dc8</guid>
            <category><![CDATA[java-records]]></category>
            <category><![CDATA[java-class]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Ayoub Taouam]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 11:45:17 GMT</pubDate>
            <atom:updated>2026-02-11T11:45:17.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*krgMLegI-o_CfK8gPNOXAw.png" /></figure><p>For years, Java Developers have written the same kind of code again… and again… and again.</p><p>Fields.</p><p>Constructor.</p><p>Getters.</p><p>equals()</p><p>hashCode()</p><p>toString()</p><p>All just to represent data.</p><p>Java Records were introduced to finally say:</p><blockquote>“If this class is just data, let’s treat as data.”</blockquote><p>This article explains what <strong>records</strong> are, why they exist, how they work and when you should use them instead of traditional POJOs.</p><h3>The Problem with Traditional POJOs</h3><p>Let’s strat with a classic POJO:</p><pre>public class User {<br>    private final String username;<br>    private final String email;<br><br>    public User(String username, String email) {<br>        this.username = username;<br>        this.email = email;<br>    }<br><br>    public String getUsername() {<br>        return username;<br>    }<br><br>    public String getEmail() {<br>        return email;<br>    }<br><br>    @Override<br>    public boolean equals(Object o) {<br>        // implementation<br>    }<br><br>    @Override<br>    public int hashCode() {<br>        // implementation<br>    }<br><br>    @Override<br>    public String toString() {<br>        // implementation<br>    }<br>}</pre><p>This class doesn’t do anything.</p><p>It simply <strong>carries data</strong>.</p><p>Yet we’re forced to write a lot of boilerplate code just to express that idea.</p><p>Java Records exist to eliminate this noise.</p><h3>What Is a Java Record?</h3><p>A record is a special kind of class introduced in Java 16 (previewed earlier) designed specifically for <strong>immutable data carriers</strong>.</p><p>The same User class as a record:</p><pre>public record User(String username, String email) {}</pre><p>That’s it.</p><p>And Java automatically generates:</p><ul><li>A constructor</li><li>Getter-like accessors (username(), email())</li><li>equals()</li><li>hashCode()</li><li>toString()</li></ul><p>All correctly implemented.</p><p>Think of it as:</p><ul><li><strong>Class</strong>: “An object with behavior and state”</li><li><strong>Record</strong>: “A named tuple with meaning”</li></ul><p>If you would describe the object as:</p><blockquote>“It’s just data”</blockquote><p>Then a record is probably the right choice.</p><h3>What Records Are Really Saying</h3><p>When you declare a record, you are telling the compiler:</p><blockquote>“This class represents a fixed set of values.</blockquote><blockquote>Identity is based on data, not behavior.”</blockquote><p>This a <strong>semantic statement</strong>, not just a syntax shortcut.</p><h4>Immutability by Design</h4><p>Records are implicitly immutable:</p><ul><li>All fields are private final</li><li>No setters</li><li>State cannot change after construction</li></ul><p>Example:</p><pre>User user = new User(&quot;alice&quot;, &quot;alice@mail.com&quot;);<br>user.username = &quot;bob&quot;; // Not allowed</pre><p>Immutability brings major benefits:</p><ul><li>Thread safety</li><li>Predictable behavior</li><li>Safer use in collection</li><li>Easier reasoning and testing</li></ul><p>This makes records perfect for DTOs, API responses and value objects.</p><h4>Accessing Data in Records</h4><p>Instead of getters, records use <strong>accessors methods</strong> with the same name as the fields:</p><pre>User user = new User(&quot;alice&quot;, &quot;alice@mail.com&quot;);<br><br>user.username(); // &quot;alice&quot;<br>user.email();    // &quot;alice@mail.com&quot;</pre><p>This may feel unusual at first, but it aligns well with the idea that records represent <em>data</em>, not behavior-heavy objects.</p><p>Records are <strong>not replacements for all classes</strong>, they are replacements for <em>specific kinds</em> of classes.</p><h3>When Records Shine</h3><h4>DTOs (Data Transfer Objects)</h4><p>Perfect fit:</p><pre>public record UserDto(Long id, String username) {}</pre><ul><li>Clean</li><li>Immutable</li><li>Serializable-friendly</li><li>Clear intent</li></ul><p>Spring, Jackson and most frameworks support records out of the box.</p><h4>API Responses</h4><p>Instead of verbose reponse classes:</p><pre>public record ApiResponse&lt;T&gt;(boolean success, T data, String error) {}</pre><p>This improves readability and consistency instantly.</p><h4>Value Objects</h4><p>If equality is based on values, not identity:</p><pre>public record Money(BigDecimal amount, Currency currency) {}</pre><p>Records generate correct equals() and hashcode() automatically, no mistakes.</p><h3>When Not to Use Records</h3><p>Records are not a silver bullet.</p><p>Avoid records when:</p><h4>Your Class Has behavior-Rich Logic</h4><p>If the class:</p><ul><li>Mutates states</li><li>Has lifecycly rules</li><li>Encapsulates complex logic</li></ul><p>Use a regular class.</p><p>Records are about <strong>representation</strong>, not behavior.</p><h4>You Need Inheritance</h4><p>Records:</p><ul><li>Cannot extend other classes</li><li>Are implicitly final</li></ul><p>If polymorphism is central to your design, records are the wrong tool.</p><h4>JPA Entities</h4><p>This is a big one.</p><p>Most JPA implementations:</p><ul><li>Require no-args constructors</li><li>Rely on proxies</li><li>Expect mutable fields</li></ul><p><strong>Records ARE NOT suitable as JPA entities</strong>.</p><p>Use them instead as:</p><ul><li>Projection results</li><li>Read-only DTOs</li><li>API layer models</li></ul><h3>Custom Logic Inside Records (Yes, You Can)</h3><p>Records can still have:</p><ul><li>Validation</li><li>Compact constructors</li><li>Methods</li></ul><p>Example:</p><pre>public record User(String username, String email) {<br><br>    public User {<br>        if (username == null || username.isBlank()) {<br>            throw new IllegalArgumentException(&quot;Username cannot be empty&quot;);<br>        }<br>    }<br><br>    public boolean isCorporateEmail() {<br>        return email.endsWith(&quot;@company.com&quot;);<br>    }<br>}</pre><p>Rules:</p><ul><li>You can add methods</li><li>You can validate</li><li>You cannot add mutable fields</li></ul><p>This keeps records <strong>safe</strong> but <strong>flexible</strong>.</p><h3>Records and JSON (Spring &amp; Jackson)</h3><p>Jackson supports records naturally:</p><pre>@PostMapping(&quot;/users&quot;)<br>public User createUser(@RequestBody User user) {<br>    return user;<br>}</pre><p>No extra annotations required.</p><p>This makes records extremely attractive for <strong>REST APIs</strong>.</p><h3>Wrap Up</h3><p>Java Records are not about saving keystrokes, they are about making intent explicit:</p><ul><li>This is data</li><li>It is immutable</li><li>Equality matters</li><li>Behavior is secondary</li></ul><p>Used correctly, records lead to:</p><ul><li>Cleaner APIs</li><li>Safer concurrency</li><li>Less boilerplate</li><li>More expressive code</li></ul><p>Used incorrectly, they might feel restrictive, the key is to know when to use them and when not to.</p><p><em>Follow for more!!!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c4745ea5dc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security: Cryptography Basics and Integration with Spring]]></title>
            <link>https://medium.com/@ayoubtaouam/spring-security-cryptography-basics-and-integration-with-spring-69959ba1972f?source=rss-8e17f7fd0be8------2</link>
            <guid isPermaLink="false">https://medium.com/p/69959ba1972f</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[hashing]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Ayoub Taouam]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 12:56:17 GMT</pubDate>
            <atom:updated>2026-02-10T12:56:17.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mre28kL8wO-rEq4xdczP3g.png" /></figure><p>Security often feels mysterious.</p><p>People throw around words like <em>encryption</em>, <em>hashing</em>, <em>keys</em>, <em>certificates</em> and <em>tokens </em>and many developers and up using cryptography without truly understanding what’s happening underneath.</p><p>This article demystifies <strong>cryptography</strong> basics in Java, explains why different cryptographic tools exist and shows how Spring (and Spring Security) integrate them in real applications, using simple explanations and concrete examples.</p><p>No math-heavy theory, just practical understanding.</p><h3>Why Cryptography Exists (The Big Picture)</h3><p>At its core, cryptography answers three fundamental questions:</p><ol><li>Can I keep data secret? → Encryption</li><li>Can I detect if data was changed? → Hashing &amp; Integrity</li><li>Can I prove who sent this data? → Signatures &amp; Authentication</li></ol><p>Think of cryptography as the <strong>locks</strong>, <strong>seals</strong> and <strong>signatures</strong> of the digital world.</p><h3>Encryption vs Hashing</h3><p>This confusion causes more security bugs than almost anything else.</p><h4>Encryption: Locking and unlocking data</h4><p>Encryption is like putting data in a <strong>safe</strong>, you can <strong>lock</strong> it, and then <strong>unlock</strong> it with the right <strong>key</strong>.</p><p>It is used when data must be <strong>stored securely</strong>, or when data must be <strong>sent</strong> over <strong>untrusted networks</strong>.</p><p>Examples:</p><ul><li>HTTPS traffic</li><li>Encrypted files</li><li>Secure messages</li></ul><p>It is <strong>Reversible</strong>.</p><h4>Hashing: Creating a Fingerprint</h4><p>Hashing is like turning data into a <strong>fingerprint</strong>.</p><ul><li>Same input → same hash</li><li>Tiny change → completely different hash</li><li>Impossible (in practice) to reverse</li></ul><p>It is used when you <strong>don’t need </strong>the original data <strong>back</strong>, or you just want to <strong>verify</strong> it.</p><p>A classic example is password storage.</p><p>It is <strong>One-way only.</strong></p><h4>Golden Rule</h4><blockquote><strong><em>Passwords should be hashed, not encrypted</em></strong></blockquote><p>If you can decrypt passwords, attackers can too.</p><h3>Symmetric vs Asymmetric Encryption</h3><h4>Symmetric Encryption: One shared Key</h4><p>Both sides use<strong> the same key</strong> to encrypt and decrypt. It‘s like a <strong>house key</strong>, anyone with the same key can <strong>lock</strong> and <strong>unlock</strong> the door.</p><p>Pros:</p><ul><li>Fast</li><li>Efficient</li></ul><p>Cons:</p><ul><li>Key sharing is risky</li></ul><h4>Asymmetric Encryption: Public &amp; Private Keys</h4><p>Two keys:</p><ul><li><strong>Public key</strong> → shared with everyone</li><li><strong>Private key</strong> → kept secret</li></ul><p>It’s like a <strong>mailbox</strong>, anyone can drop a letter in (<strong>public key</strong>), but only the owner can open it (<strong>private key</strong>).</p><p>Pros:</p><ul><li>Solves key-sharing problem</li><li>Enables identity verification</li></ul><p>Cons:</p><ul><li>Slower than symmetric encryption</li></ul><h4>Why Not Both?</h4><p>HTTPS uses:</p><ul><li>Asymmetric encryption → exchange a secret</li><li>Symmetric encryption → encrypt actual data</li></ul><p>Best of both worlds.</p><h3>Hashing in Java</h3><p>Java provides hashing via standard libraries, but Spring Security makes it safer and easier.</p><h4>Never</h4><pre>MessageDigest md = MessageDigest.getInstance(&quot;SHA-256&quot;);</pre><p>SHA-256 alone is not enough for passwords, cause it is too fast, and vulnerable to brute-force attacks.</p><h4>The Right Way: Password Encoders</h4><p>Spring Security provides battle-tested encoders:</p><pre>@Bean<br>public PasswordEncoder passwordEncoder() {<br>    return new BCryptPasswordEncoder();<br>}</pre><p>Usage:</p><pre>String hash = passwordEncoder.encode(password);<br>boolean matches = passwordEncoder.matches(raw, hash);</pre><p>Why BCrypt?</p><ul><li>Slow by design</li><li>Automatically salts passwords</li><li>Resistant to rainbow tables</li></ul><h3>Digital Signatures</h3><p>Encryption protects <strong>secrecy</strong>.</p><p>Signatures protect <strong>trust</strong>.</p><p>A digital signature proves:</p><ul><li>Who sent the data</li><li>That it wasn’t modified</li></ul><p>Think of it as a handwritten signature on a contract, anyone can read the contract, only the signer could have signed it.</p><p>Used in:</p><ul><li>JWTs</li><li>OAuth tokens</li><li>Certificates</li><li>Secure APIs</li></ul><h3>Cryptography in Spring Applications</h3><p>You might not realize it, but Spring uses cryptography everywhere.</p><h4>1. HTTPS and TLS</h4><p>When you run Spring Boot with HTTPs:</p><ul><li>Certificates use asymmetric cryptography</li><li>Data is encrypted symmetrically</li><li>Integrity is constantly verified</li></ul><p>You don’t implement this, Spring + JVM handle it.</p><h4>2. Password Storage</h4><p>Spring Security:</p><ul><li>Hashes passwords</li><li>Compares hashes</li><li>Never exposes raw credentials</li></ul><p>This is cryptography working <strong>silently but critically</strong>.</p><h4>3. JWT Authentication</h4><p>JWTs use:</p><ul><li>Base64 encoding (not encryption)</li><li>Cryptographic signatures</li></ul><p>Spring Security:</p><ul><li>Validates signatures</li><li>Ensures tokens weren’t altered</li><li>Extracts identity securely</li></ul><h4>4. Secure Configuration</h4><p>Spring supports:</p><ul><li>Encrypted properties</li><li>External secret managers</li><li>Environment-based isolation</li></ul><p>Cryptography protects:</p><ul><li>Database passwords</li><li>API keys</li><li>Tokens</li></ul><h3>Wrap Up</h3><p>Cryptography doesn’t have to be scary, you don’t need to:</p><ul><li>Invent algorithms</li><li>Understand complex math</li><li>Manage keys manually</li></ul><p>You do need to:</p><ul><li>Understand the purpose of each tool</li><li>Use the right abstraction</li><li>Let Spring and the JVM do the heavy lifting</li></ul><p>When used correctly, cryptography becomes an invisible foundation, quietly protecting your users, your data and your systems.</p><p><em>Follow for more!!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69959ba1972f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[N+1 Queries: How They Appear and How to Spot Them Early]]></title>
            <link>https://medium.com/@ayoubtaouam/n-1-queries-how-they-appear-and-how-to-spot-them-early-2a04fde40288?source=rss-8e17f7fd0be8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a04fde40288</guid>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[jpa]]></category>
            <category><![CDATA[n-plus-1-queries]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ayoub Taouam]]></dc:creator>
            <pubDate>Mon, 09 Feb 2026 17:10:53 GMT</pubDate>
            <atom:updated>2026-02-09T17:10:53.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xC3tCVKWTwbpvCie64xByw.png" /></figure><p>Few problems in backend development are as common and as sneaky as the <strong>N+1 query problem</strong>.</p><p>Your code works.</p><p>Your tests pass.</p><p>Your data looks correct.</p><p>And yet… Your API slows down dramatically as data grows.</p><p>This article explains what <strong>N+1 queries</strong> are, why they happen, how to recognize them early and how to fix them.</p><h3>First: What Is an N+1 Query?</h3><p>At its core, the N+1 problem is <strong>inefficient data fetching</strong>.</p><h4>The Pattern</h4><ol><li>You run <strong>1 query</strong> to fetch a list of entities</li><li>Then, for <strong>each entity</strong>, you run <strong>another query</strong> to fetch related data</li></ol><p>Total queries:</p><pre>1 + N</pre><p>Where N is the number of entities returned by the first query.</p><p>It’s like you’re a waiter, and you go to the kitchen once to get a list of tables (1 query), then for each table, you go back to the kitchen to ask: <em>“What did this table order?”</em></p><p>That’s:</p><ul><li>1 trip to get he tables</li><li>N trips to get the orders</li></ul><p>Now imagine 100 tables, your legs hurt, your restaurant is slow and your manager is not happy.</p><p>That’s N+1.</p><h3>A Concrete Example (Java + JPA)</h3><p>Let’s say we have:</p><ul><li>User</li><li>Order</li></ul><p>Each user can have multiple orders.</p><pre>@Entity<br>class User {<br>    @Id<br>    Long id;<br><br>    String name;<br><br>    @OneToMany(mappedBy = &quot;user&quot;)<br>    List&lt;Order&gt; orders;<br>}</pre><p>Now, in your service:</p><pre>List&lt;User&gt; users = userRepository.findAll();<br><br>for (User user : users) {<br>    System.out.println(user.getOrders().size());<br>}</pre><h4>What You Think Happens</h4><blockquote>“Hibernate will fetch everything efficiently.”</blockquote><h4>What Actually Happens</h4><p>Query #1:</p><pre>SELECT * FROM users;</pre><p>Then, for each user:</p><pre>SELECT * FROM orders WHERE user_id = ?;</pre><p>If you fetched 50 users:</p><ul><li>1 query for users</li><li>50 queries for orders</li></ul><p>→ <strong>51 queries total</strong></p><p>That’s the N+1 problem.</p><h3>Why N+1 Queries Are So Dangerous</h3><h4>1. They Scale Horribly</h4><p>The bigger your data set, the worse it gets.</p><ul><li>10 users → 11 queries</li><li>100 users → 101 queries</li><li>1000 users → 1001 queries</li></ul><p>Performance degrades linearly, sometimes exponentially depending on joins.</p><h4>2. They Hide in Plain Sight</h4><p>N+1 problems:</p><ul><li>Don’t throw exceptions</li><li>Don’t break functionality</li><li>Often don’t show up in small test databases</li></ul><p>They appear <strong>only when real data arrives</strong>.</p><h4>3. They Destroy Latency</h4><p>Each query:</p><ul><li>Has network overhead</li><li>Competes for DB connections</li><li>Adds parsing and execution time</li></ul><p>Many small queries are often <strong>worse</strong> than one big query.</p><h3>Why ORMs Are Often Involved (But Not the Villain)</h3><p>ORMs like Hibernate or JPA are powerful, but they rely on <strong>lazy loading</strong> by default.</p><h4>Lazy Loading (Quick Explanation)</h4><p>Lazy loading means:</p><blockquote>“Don’t fetch related data until it’s actually used.”</blockquote><p>Sounds smart, and it often is.</p><p>But combined with loops, it creates N+1 queries.</p><h4>Example of Lazy Loading</h4><pre>user.getOrders(); // triggers a query if orders are lazy</pre><p>Inside a loop, that’s a disaster.</p><h3>How to Spot N+1 Queries Early</h3><h4>1. Enable SQL Logging</h4><p>In Spring Boot:</p><pre>spring.jpa.show-sql=true<br>spring.jpa.properties.hibernate.format_sql=true</pre><p>Now watch the logs.</p><p>If you see:</p><ul><li>One SELECT for a list</li><li>Followed by dozens of similar SELECTs</li></ul><p>You’ve found an N+1.</p><h4>2. Look for loops That Access Relations</h4><p>Any code like this is suspicious:</p><pre>for (Entity e : entities) {<br>    e.getRelation();<br>}</pre><p>Especially in:</p><ul><li>Controllers</li><li>DTO mappers</li><li>JSON serialization</li></ul><h4>3. Use Performance Profiles or APM Tools</h4><p>Tools like:</p><ul><li>Hibernate statistics</li><li>Application Performance Monitoring (APM)</li><li>DB query logs</li></ul><p>They show:</p><ul><li>Query counts</li><li>Execution times</li><li>Repeats patterns</li></ul><p>N+1 stands out very clearly there.</p><h3>How to Fix The N+1 Problem</h3><h4>Solution 1: Fetch Joins</h4><p>Tell Hibernate upfront:</p><blockquote>“I need this data together.”</blockquote><pre>@Query(&quot;&quot;&quot;<br>SELECT u FROM User u<br>JOIN FETCH u.orders<br>&quot;&quot;&quot;)<br>List&lt;User&gt; findAllWithOrders();</pre><p>This results in:</p><pre>SELECT users.*, orders.*<br>FROM users<br>JOIN orders ON ...</pre><ul><li>One query</li><li>All data loaded</li><li>No surprises</li></ul><h4>Solution 2: Entity Graphs (Cleaner, More Flexible)</h4><pre>@EntityGraph(attributePaths = &quot;orders&quot;)<br>List&lt;User&gt; findAll();</pre><ul><li>Keeps your entities clean</li><li>Avoids writing JPQL</li><li>Is great for reusable repositories</li></ul><h4>Solution 3: DTO Projections</h4><p>Instead of loading entities:</p><pre>SELECT new UserOrderDTO(u.name, o.id)<br>FROM User u JOIN u.orders o</pre><ul><li>Fetch only what you need</li><li>No lazy loading</li><li>No N+1</li><li>Better API design</li></ul><h3>Wrap Up</h3><p>Fixing N+1 doesn’t mean:</p><blockquote>“Always fetch everything eagerly”</blockquote><p>That creates:</p><ul><li>Huge joins</li><li>Memory waste</li><li>Slower queries</li></ul><p>The goal is <strong>intentional data fetching</strong>.</p><p>N+1 queries are a performance bug, not a syntax bug, easy to write and hard to notice.</p><p>ORMs make them possible, not inevitable, and only logging and awareness catch them early.</p><p>Fetch joins, entity graph and DTOs are your main weapons.</p><p>Once you start seeing N+1 problems, you’ll notice them everywhere and your systems will instantly become faster and more predictable.</p><p><em>Follow for more!!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a04fde40288" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Large Payloads in REST APIs Without Killing Performance]]></title>
            <link>https://medium.com/@ayoubtaouam/handling-large-payloads-in-rest-apis-without-killing-performance-02875e16737f?source=rss-8e17f7fd0be8------2</link>
            <guid isPermaLink="false">https://medium.com/p/02875e16737f</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[chunking]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[streaming]]></category>
            <dc:creator><![CDATA[Ayoub Taouam]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 12:36:42 GMT</pubDate>
            <atom:updated>2026-02-05T12:36:42.759Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2z13ZuLAbsnIoJZEBt0eQ.png" /></figure><p>Modern APIs don’t just move small JSON objects anymore, they stream videos, upload CSVs with millions of rows, exchange large reports, images, PDFs and analytics data.</p><p>And this is where many REST APIs quietly die:</p><ul><li>Memory spikes</li><li>Slow responses</li><li>Timeouts</li><li>Crashed servers</li><li>Angry users</li></ul><p>This article explains why large payloads are dangerous, what actually goes wrong under the hood and how to handle them safely and efficiently, especially in Java and Spring Boot.</p><h3>The Core Problem: Large Payloads Stress Every Layer</h3><p>Think of your API like a <strong>restaurant kitchen</strong>.</p><ul><li>A normal request is a single plate → easy to prepare and serve</li><li>A large payload is someone ordering <strong>food for 200 people at once</strong></li></ul><p>The problem isn’t just the food, it’s:</p><ul><li>Storage</li><li>Preparation</li><li>Timing</li><li>Coordination</li><li>Cleanup</li></ul><p>Large payloads put pressure on:</p><ul><li>Network</li><li>Memory (RAM)</li><li>CPU</li><li>Serialization / deserialization</li><li>Databases</li><li>Downstream services</li></ul><p>If you don’t handle them intentionally, your API becomes fragile.</p><h3>Why Large Payloads Are Especially Dangerous in REST APIs</h3><h4>1. Memory Explosion</h4><p>By default, many frameworks:</p><ul><li>Read the entire request body into memory</li><li>Parse it fully before your code runs</li></ul><p>If a client sends a 200MB payload:</p><ul><li>That 200MB sits in RAM</li><li>Often duplicated during parsing</li><li>Multiplied by concurrent requests</li></ul><p>Result: OutOfMemoryError or severe GC pressure.</p><h4>2. Blocking Threads</h4><p>Traditional servlet-based APIs (like Spring MVC):</p><ul><li>Use one thread per request</li><li>That thread is blocked while reading the payload</li></ul><p>Large payload = long-lived thread</p><p>Many large payloads = thread starvation</p><p>Your API stops responding, even for small requests.</p><h4>3. Slow Serialization &amp; Deserialization</h4><p>JSON is human-friendly, but:</p><ul><li>It’s verbose</li><li>Parsing is CPU-heavy</li><li>Large nested objects take to map into memory</li></ul><p>The bigger the payload, the more time spent <strong>just converting bytes into objects</strong>.</p><h4>4. Network Latency and Timeouts</h4><p>Large payloads:</p><ul><li>Take longer to upload/download</li><li>Are more sensitive to unstable connections</li><li>Increase timeout risks</li></ul><p>Clients retry, servers reprocess → chaos.</p><h3>Golden Rule: Avoid Large Payloads If You Can</h3><p>Before optimizing, ask this blunt question:</p><blockquote><strong><em>Do I really need to send all this data at once?</em></strong></blockquote><p>Often the answer is <strong>no</strong>.</p><h4>Common Anti-Patterns</h4><ul><li>Sending full object when only IDs are needed</li><li>Returning entire database rows “just in case”</li><li>One endpoint doing too much</li></ul><h4>Better Alternatives</h4><ul><li>Pagination</li><li>Filtering &amp; projections</li><li>Partial responses</li><li>Separate endpoints for heavy data</li></ul><p>Example:</p><pre>GET /users?fields=id,name,email</pre><p>Instead of:</p><pre>GET /users</pre><h3>Strategy 1: Pagination Is Non-Negotiable</h3><p>Pagination is the seatbelt of REST APIs.</p><h4>Why Pagination Matters</h4><ul><li>Limits memory usage</li><li>Reduces response size</li><li>Improves perceived performance</li><li>Protects your database</li></ul><h4>Spring Boot Example</h4><pre>@GetMapping(&quot;/orders&quot;)<br>public Page&lt;Order&gt; getOrders(Pageable pageable) {<br>    return orderRepository.findAll(pageable);<br>}</pre><p>This:</p><ul><li>Fetches only what’s needed</li><li>Streams results from the database efficiently</li><li>Prevents accidental data floods</li></ul><h3>Strategy 2: Streaming Instead of Loading Everything</h3><h4>The Key Idea</h4><blockquote><strong><em>Process data as a stream, not as a blob</em></strong></blockquote><p>Think of blob approach as filling a swimming pool before drinking, and streaming as sipping from a straw.</p><h4>Streaming Downloads (Spring MVC)</h4><pre>@GetMapping(&quot;/download&quot;)<br>public ResponseEntity&lt;StreamingResponseBody&gt; download() {<br>    StreamingResponseBody stream = outputStream -&gt; {<br>        // write chunks to outputStream<br>    };<br><br>    return ResponseEntity.ok(stream);<br>}</pre><ul><li>Data is sent in chunks</li><li>Minimal memory usage</li><li>Faster first byte to client</li></ul><h4>Streaming Uploads</h4><p>Instead of:</p><pre>@RequestBody byte[] data</pre><p>Use:</p><pre>@RequestParam MultipartFile file</pre><p>Or directly stream input:</p><pre>InputStream inputStream = request.getInputStream();</pre><p>This avoids loading the entire file into memory.</p><h3>Strategy 3: Prefer Binary Over JSON for Large Data</h3><p>JSON is great, until it’s not.</p><h4>When JSON Becomes a Problem</h4><ul><li>Large arrays</li><li>Repetitive field names</li><li>Deep nesting</li></ul><h4>Better Alternatives</h4><ul><li><strong>Binary formats</strong> (Protobuf)</li><li><strong>CSV</strong> for bulk data</li><li><strong>Files + metadata API</strong></li></ul><p>Example:</p><ol><li>Upload file → get file ID</li><li>Process asynchronously</li><li>Query status via REST</li></ol><p>This decouples heavy data from request lifecycle.</p><h3>Strategy 4: Asynchronous Processing</h3><p>Large payloads often mean <strong>long processing</strong>.</p><p>Don’t make the client wait.</p><h4>Bad Pattern</h4><p>Client → upload → server processes everything → response</p><h4>Better Pattern</h4><ol><li>Client uploads data</li><li>Server returns 202 Accepted</li><li>Processing happens asynchronously</li><li>Client polls or receives callback</li></ol><p>Think of it as dropping off laundry instead of waiting at the washing machine.</p><h4>Spring Example (conceptual)</h4><pre>@PostMapping(&quot;/import&quot;)<br>public ResponseEntity&lt;Void&gt; importData(@RequestParam MultipartFile file) {<br>    importService.processAsync(file);<br>    return ResponseEntity.accepted().build();<br>}</pre><h3>Strategy 5: Enforce Size Limits (Protect Yourself)</h3><p>Never trust clients.</p><h4>Spring Boot Configuration</h4><pre>spring.servlet.multipart.max-file-size=10MB<br>spring.servlet.multipart.max-request-size=10MB</pre><p>Also enforce:</p><ul><li>Gateway limits</li><li>Reverse proxy limits</li><li>Application-level validation</li></ul><p>This is <strong>defensive programming</strong>, not rudeness.</p><h3>Strategy 6: Use Backpressure and Reactive APIs When Needed</h3><p>For high-throughput systems:</p><ul><li>Reactive programming (Spring WebFlux)</li><li>Non-blocking I/O</li><li>Backpressure-aware streams</li></ul><p>This allows:</p><ul><li>Thousands of concurrent usage</li><li>Minimal thread usage</li><li>Better resource control</li></ul><p>But:</p><blockquote>Reactive is powerful, not magical</blockquote><blockquote>Use it intentionally, not by default</blockquote><h3>Strategy 7: Don’t Let Databases Be the Bottleneck</h3><p>Large payloads often mean large DB writes.</p><h4>Common Mistakes</h4><ul><li>Saving row-by-row</li><li>No batching</li><li>No transaction control</li></ul><h4>Better Approach</h4><ul><li>Batch inserts</li><li>Chunked processing</li><li>Clear transactional boundaries</li></ul><p>This protects:</p><ul><li>DB performance</li><li>Locks</li><li>Rollbacks</li></ul><h3>You Can’t Fix What You Can’t See</h3><p>When dealing with large payloads, always monitor:</p><ul><li>Request size</li><li>Response size</li><li>Processing time</li><li>Memory usage</li><li>GC behavior</li></ul><p>Logs + metrics = survival kit.</p><h3>Wrap Up</h3><p>Think of large payload handling like moving furniture:</p><ul><li>You don’t carry everything at once</li><li>You don’t block the hallway</li><li>You plan the route</li><li>You protect your back</li><li>You use tools instead of brute force</li></ul><p>APIs work the same way.</p><p>If you handle large payloads intentionally, your API stays fast, stable and scalable, even under pressure.</p><p><em>Follow for more!!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02875e16737f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Security vs Web Security: Same Goal, Very Different Problems]]></title>
            <link>https://medium.com/@ayoubtaouam/api-security-vs-web-security-same-goal-very-different-problems-33d26225c690?source=rss-8e17f7fd0be8------2</link>
            <guid isPermaLink="false">https://medium.com/p/33d26225c690</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[api-security]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[spring-security]]></category>
            <dc:creator><![CDATA[Ayoub Taouam]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 15:22:55 GMT</pubDate>
            <atom:updated>2026-02-03T15:22:55.723Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48a9btnUGaZD6usogcLCJw.png" /></figure><p>When people talk about security, they often mix these two things together:</p><ul><li><strong>Web Security</strong></li><li><strong>API Security</strong></li></ul><p>They sound similar.</p><p>They both involve authentication, authorization and protection, but in practice?</p><blockquote><strong><em>They solve very different problems, for very different clients, in very different ways.</em></strong></blockquote><p>Treating them as the same thing is one of the most common security mistakes in modern systems.</p><p>Let’s break it down, clearly and calmly.</p><h3>First: What Do We Mean by “Web” and “API”?</h3><p>Before security, we need clarity.</p><h4>Web Application (Browser-Based)</h4><p>A <strong>Web Application</strong> is:</p><ul><li>Used by humans</li><li>Accessed via a browser</li><li>Stateful by nature</li><li>Built around pages, forms and sessions.</li></ul><p>Examples:</p><ul><li>Online banking website</li><li>Admin dashboard</li><li>E-commerce site</li></ul><h4>API (Machine-to Machine)</h4><p>An <strong>API</strong> is:</p><ul><li>Used by software, not humans</li><li>Accessed programmatically</li><li>Often stateless</li><li>Built around requests and responses</li></ul><p>Examples:</p><ul><li>Mobile app backend</li><li>Public REST API</li><li>Microservice communication</li></ul><p>Same server, same data, completely different interaction models.</p><h3>A Simple Analogy: Reception Desk vs Keycard System</h3><h4>Web Security = Reception Desk</h4><ul><li>A person walks in</li><li>Shows ID</li><li>Gets a badge</li><li>Badge is reused during the visit</li></ul><p>This is how <strong>web security</strong> works:</p><ul><li>Login form</li><li>Session cookie</li><li>Server remembers who you are</li></ul><h4>API Security = Keycard Scanner</h4><ul><li>No conversation</li><li>No memory</li><li>Each access must present proof</li><li>Proof is verified every time</li></ul><p>This is <strong>API security</strong>:</p><ul><li>Tokens</li><li>API keys</li><li>Cryptographic validation</li></ul><h3>Web Security: Design for Humans</h3><p>Web security assumes:</p><ul><li>A browser</li><li>A user sitting behind a screen</li><li>Cookies and redirects are acceptable</li></ul><h4>Common Web Security Characteristics</h4><ul><li>Session-based authentication</li><li>Cookies automatically sent by the browser</li><li>CSRF protection</li><li>Login pages and redirects</li><li>Logout endpoints</li></ul><h4>Why Sessions Make Sense Here</h4><p>Sessions:</p><ul><li>Store identity on the server</li><li>Reduce repeated authentication</li><li>Make UX smoother</li></ul><p>This is prefect for:</p><blockquote><em>Long-lived user interactions</em></blockquote><h3>API Security: Designed for Software</h3><p>APIs assume:</p><ul><li>No browser</li><li>No cookies</li><li>No redirects</li><li>No memory between requests</li></ul><h4>Common API Security Characteristics</h4><ul><li>Token-based authentication (JWT, OAuth2)</li><li>Each request carries credentials</li><li>Stateless verification</li><li>Explicit error responses (401, 403)</li><li>No UI assumptions</li></ul><p>APIs must work for:</p><ul><li>Mobile apps</li><li>Frontend SPAs</li><li>Other backend services</li></ul><h3>Why Mixing Them Is Dangerous</h3><h4>Using Web Security for APIs</h4><p>Problems:</p><ul><li>CSRF protection makes no sense</li><li>Session state doesn’t scale</li><li>Cookies don’t work reliably</li><li>Hard to secure mobile clients</li></ul><h4>Using API Security for Web Apps</h4><p>Problems:</p><ul><li>Poor user experience</li><li>Frequent re-authentication</li><li>No session continuity</li><li>Harder logout semantics</li></ul><p>Different problems require <strong>different solutions</strong>.</p><h3>Authentication: Same Goal, Different Execution</h3><h4>Web Authentication</h4><ul><li>Username + password</li><li>Server creates a session</li><li>Session ID stored in cookie</li><li>Cookie sent automatically</li></ul><p>Identity lives <strong>on the server</strong>.</p><h4>API Authentication</h4><ul><li>Token issued after login</li><li>Token sent in headers</li><li>Token validated cryptographically</li><li>No server-side session</li></ul><p>Identity lives <strong>inside the token</strong>.</p><h3>Authorization: Similar Rules, Different Context</h3><p>Both web and API security need authorization:</p><ul><li>Roles</li><li>Permissions</li><li>Access rules</li></ul><p>But enforcement differs.</p><h4>Web Authorization</h4><ul><li>Page-level access</li><li>Button visibility</li><li>View-based security</li></ul><h4>API Authorization</h4><ul><li>Endpoint-level access</li><li>HTTP method restrictions</li><li>Scope-based rules</li></ul><p>APIs require <strong>precision</strong> because there is no UI layer to hide mistakes.</p><h3>Error Handling: UX vs Protocol</h3><h4>Web Security Errors</h4><ul><li>Redirect to login</li><li>Show error pages</li><li>Friendly messages</li></ul><h4>API Security Errors</h4><ul><li>HTTP status codes</li><li>JSON error responses</li><li>Machine-readable messages</li></ul><p>An API should never:</p><blockquote><em>Redirect, render HTML or assume a browser</em></blockquote><h3>Scalability: Where the Big Difference Appears</h3><h4>Web Security Scalability</h4><p>Sessions:</p><ul><li>Require memory or storage</li><li>Need replication in clusters</li><li>Can become bottlenecks</li></ul><h4>API Security Scalability</h4><p>Stateless tokens:</p><ul><li>No server memory needed</li><li>Horizontally Scalable</li><li>Cloud-native by design</li></ul><p>This is why:</p><blockquote><em>Modern distributed systems almost always favor token-based API security</em></blockquote><h3>Wrap Up</h3><p>API security and web security are not competitors, they are <strong>specialists</strong> solving different problems.</p><p>When you design security with the right model:</p><ul><li>Your system becomes safer</li><li>Your architecture becomes clearer</li><li>Your code becomes easier to reason about</li></ul><p>Security isn’t just about protection.</p><blockquote><strong><em>It’s about choosing the right guard for the right door.</em></strong></blockquote><p><em>Follow for more!!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33d26225c690" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What actually Happens When You Start a Spring Boot Application]]></title>
            <link>https://medium.com/@ayoubtaouam/what-actually-happens-when-you-start-a-spring-boot-application-9b85421709b5?source=rss-8e17f7fd0be8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b85421709b5</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[application-startup]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[application-context]]></category>
            <category><![CDATA[spring-framework]]></category>
            <dc:creator><![CDATA[Ayoub Taouam]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 16:49:01 GMT</pubDate>
            <atom:updated>2026-01-22T16:49:01.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T2c4dwH0TXscCkefxhJrtQ.png" /></figure><p>You’ve probably written this line hundreds of times:</p><pre>SpringApplication.run(MyApplication.class, args);</pre><p>And watched your application start…</p><p>With logs flying by…</p><p>Beans being created…</p><p>Ports opening…</p><p>It works, but what <em>actually </em>happens?</p><p>Spring Boot is famous for feeling like magic.</p><p>But it isn’t magic. It’s <strong>a very well-orchestrated startup process</strong>.</p><p>Let’s break it down.</p><h3>The Journey Begins: main()</h3><p>Every Spring Boot application starts like any other Java program:</p><pre>public static void main(String[] args) {<br>    SpringApplication.run(MyApplication.class, args);<br>}</pre><p>At this point:</p><ul><li>Nothing Spring-specific has happened yet</li><li>No beans exist</li><li>No web server is running</li></ul><p>You’re still in <strong>plain Java land</strong>, then Spring Boot takes over.</p><h3>Creating the SpringApplication Object</h3><p>Before anything runs, Spring Boot prepares itself.</p><p>Internally, SpringApplication.run():</p><ul><li>Determines if this is a web app or not</li><li>Detects the environment (JVM, OS, properties)</li><li>Sets up bootstrap configuration</li></ul><p>Think of this as:</p><blockquote><strong><em>Spring Boot packing its tools before starting the engine</em></strong></blockquote><h3>Environment Preparation: Configuration Comes First</h3><p>Before beans exist, Spring needs to know how the application should behave, it loads:</p><ul><li>application.properties</li><li>Environment variables</li><li>JVM arguments</li><li>Command-line arguments</li></ul><p>All of these are merged into a structure called the <strong>Environment</strong>.</p><h4>What is the Environment?</h4><p>The <strong>Environment </strong>is Spring’s way of answering questions like:</p><ul><li>Which profile is active?</li><li>What is the database URL?</li><li>Is this dev or prod?</li></ul><p>Configuration is resolved <strong>before </strong>beans are created so Spring knows:</p><blockquote>Which beans should exist and how they should be configured</blockquote><h3>Creating the ApplicationContext: The Heart of Spring</h3><p>Next, Spring creates the <strong>ApplicationContext</strong>.</p><h4>What Is the ApplicationContext?</h4><p>The ApplicationContext is:</p><ul><li>A container for all Spring beans</li><li>A dependency manager</li><li>A lifecycle controller</li></ul><p>You can think of it as:</p><blockquote><strong><em>The brain of the Spring application</em></strong></blockquote><p>Once the context exists, Spring can start creating objects.</p><h3>Classpath Scanning: Finding Your Beans</h3><p>Spring now scans your application starting from:</p><pre>@SpringBootApplication</pre><p>This annotation combines:</p><ul><li>@Configuration</li><li>@EnableAuthoConfiguration</li><li>@ComponentScan</li></ul><h4>Component Scanning</h4><p>Spring looks for classes annotated with:</p><ul><li>@Component</li><li>@Service</li><li>@Repository</li><li>@Controller</li><li>@Configuration</li></ul><p>Each discovered class becomes a <strong>bean definition</strong>.</p><p>Important:</p><blockquote><em>Beans are</em> described <em>first, not created yet.</em></blockquote><h3>Auto-Configuration: Spring Boot’s Superpower</h3><p>This is where Spring Boot really shines.</p><h4>What Is Auto-Configuration?</h4><p>Auto-configuration means:</p><blockquote><strong><em>Spring configures beans automatically based on what it finds</em></strong></blockquote><p>Examples:</p><ul><li>If spring-web is on the classpath → configure MVC</li><li>If spring-data-jpa is present → configure JPA</li><li>If a database driver exists → configure a DataSource</li></ul><p>This is powered by:</p><ul><li>@EnableAutoConfiguration</li><li>Conditional annotations like @ConditionalOnClass</li></ul><p>Spring asks questions like:</p><blockquote>“Is this library present?”</blockquote><blockquote>“Has the user already defines this bean?”</blockquote><p>Only then does it create defaults.</p><h3>Bean Creation and Dependency Injection</h3><p>Now the real work begins, Spring:</p><ol><li>Instantiates beans</li><li>Resolves dependencies</li><li>Injects them into constructors or fields</li></ol><h4>Dependency Injection: Simple Definition</h4><p>Dependency Injection means:</p><blockquote><strong><em>Objects receive what they need instead of creating it themselves</em></strong></blockquote><p>Spring builds a dependency graph and ensures:</p><ul><li>Correct order</li><li>No missing dependencies</li><li>Singletons are reused</li></ul><h3>Bean Lifecycle: From Birth to Ready</h3><p>Each bean goes through stages:</p><ol><li>Instantiation (object created)</li><li>Dependency injection</li><li>Initialization callbacks</li><li>Ready for use</li></ol><p>If you use:</p><ul><li>@PostConstruct</li><li>InitializingBean</li><li>Custom init methods</li></ul><p>They run here.</p><p>Spring ensures every bean is:</p><blockquote><strong><em>Fully prepared before the application starts</em></strong></blockquote><h3>Embedded Web Server Starts: If Web App</h3><p>If this is a web application:</p><ul><li>Spring starts an embedded server (Tomcat, Jetty or Undertow)</li><li>Configures ports and context paths</li><li>Registers the DispatcherServlet</li></ul><p>At this points:</p><blockquote><strong><em>Your application is listening for HTTP requests</em></strong></blockquote><h3>Final Step: Application Ready</h3><p>Spring publishes lifecycle events like:</p><ul><li>ApplicationStratedEvent</li><li>ApplicationReadyEvent</li></ul><p>This allows:</p><ul><li>Running startup logic</li><li>Initializing data</li><li>Logging readiness</li></ul><p>Finally, you see:</p><pre>Started MyApplication in 2.345 seconds</pre><p>Your app is officially alive.</p><h3>The Whole Startup Flow: Mentally Simplified</h3><p>Think of Spring Boot startup like this:</p><ol><li>Start Java</li><li>Load configuration</li><li>Create context</li><li>Discover beans</li><li>Apply auto-configuration</li><li>Create and wire beans</li><li>Start web server</li><li>Application is ready</li></ol><p>Nothing magical, just well-ordered steps.</p><h3>Wrap Up</h3><p>Spring Boot doesn’t hide complexity, it organizes it, once you understand what happens during startup, Spring stops feeling mysterious, and that single line:</p><pre>SpringApplication.run(...)</pre><p>Stops being just a line, and starts being elegant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b85421709b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How the Spring Security Filter Chain Really Works]]></title>
            <link>https://medium.com/@ayoubtaouam/how-the-spring-security-filter-chain-really-works-5a624f984a3c?source=rss-8e17f7fd0be8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a624f984a3c</guid>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[security-filter-chain]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Ayoub Taouam]]></dc:creator>
            <pubDate>Wed, 21 Jan 2026 13:54:07 GMT</pubDate>
            <atom:updated>2026-01-21T13:54:07.010Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eKgoWM-rPTBnEYzpaQb3EQ.png" /></figure><p>If you’ve used Spring Security, you’ve probably seen this sentence somewhere:</p><blockquote>“Spring Security is based on a filter chain”</blockquote><p>And maybe you nodded, but deep down thought:</p><blockquote>Okay… but what actually happens when a request comes in?</blockquote><p>This article answers exactly that, we’ll walk step by step through:</p><ul><li>What the Spring Security filter chain is</li><li>How requests flow through it</li><li>What each major filter is responsible for</li><li>How authentication and authorization really happen</li><li>Why this design is so powerful</li></ul><h3>Start With the Big Picture</h3><p>Before touching Spring Security, let’s recall how a normal Spring Boot web app works.</p><h4>Without Spring Security</h4><pre>HTTP Request<br>   ↓<br>DispatcherServlet<br>   ↓<br>Controller<br>   ↓<br>Service / Repository</pre><p>Simple and direct. Now let’s add Spring Security.</p><h4>With Spring Security</h4><pre>HTTP Request<br>   ↓<br>Security Filter Chain<br>   ↓<br>DispatcherServlet<br>   ↓<br>Controller<br>   ↓<br>Service / Repository</pre><p><strong>Spring Security always runs before your controllers.</strong></p><p>This is not optional.</p><p>This is not configurable away.</p><p>This is intentional.</p><h3>What Is the Spring Security Filter Chain?</h3><p>The <strong>Spring Security Filter Chain</strong> is a <strong>sequence of servlet filters</strong>, each with a specific responsibility.</p><p>Instead of one big security check, Spring uses <strong>many small filters</strong>, chained together.</p><p>Each filter:</p><ul><li>Examines the request</li><li>Performs one security task</li><li>Decides whether to continue or stop the request</li></ul><p>Think of it as a <strong>security assembly line</strong>.</p><h3>Building Security Checkpoints</h3><p>Imagine entering a secure building:</p><ol><li><strong>ID Check</strong>: Who you are?</li><li><strong>Badge Validation</strong>: Is your badge valid?</li><li><strong>Permission Check</strong>: Are you allowed into this area?</li><li><strong>Final Approval</strong>: Go ahead.</li></ol><p>Each checkpoint:</p><ul><li>Has one responsibility</li><li>Passes you forward if you pass</li><li>Stops you immediately if you fail</li></ul><p>That’s exactly how the filter chain works.</p><h3>Where Does the Filter Chain Live?</h3><p>Spring Security integrates with the Servlet container (Tomcat, Jetty, etc.).</p><p>The entry point is a special filter: DelegatingFilterProxy</p><p>This filter:</p><ul><li>Is registered with the servlet container</li><li>Delegates all work to Spring-managed security filters</li><li>Bridges <strong>Servlet world </strong>→ <strong>Spring world</strong></li></ul><p>You rarely touch it directly, but it’s essential.</p><h3>The Core Flow of a Request</h3><p>Let’s walk through a typical request step by step.</p><h4>Step 1: The Request Enters the Filter Chain</h4><p>An HTTP request arrives:</p><pre>GET /api/orders<br>Authorization: Bearer eyJhbGciOi...</pre><p>before Spring MVC sees it, the request enters the <strong>security filter chain</strong>.</p><h4>Step 2: SecurityContext Is Prepared</h4><p>One of the first things Spring Security does is manage the <strong>SecurityContext</strong>.</p><p>The <strong>SecurityContext </strong>is a container that holds:</p><ul><li>Who the user is</li><li>Whether they are authenticated</li><li>What roles or authorities they have</li></ul><p>At the beginning:</p><ul><li>The context is empty</li><li>No user is authenticated yet</li></ul><h3>Authentication Filters: Who Are You?</h3><p>Authentication filers answer one question:</p><blockquote>“Can we identify this user?”</blockquote><p>Examples:</p><ul><li>Username/password login</li><li>JWT token authentication</li><li>OAuth2 login</li><li>Session-based authentication</li></ul><h4>JWT Example</h4><p>A JWT authentication filter will:</p><ol><li>Read the Authentication header</li><li>Extract the token</li><li>Validate its signature</li><li>Parse user information</li><li>Create an Authentication object</li><li>Store it in the SecurityContext</li></ol><p>If authentication fails:</p><ul><li>The filter stops the chain</li><li>A 401 Unauthorized response is returned</li></ul><h3>Once Authenticated: The SecurityContext Is Filled</h3><p>After successful authentication:</p><pre>SecurityContext<br> └── Authentication<br>     ├── Principal (user identity)<br>     ├── Roles / Authorities<br>     └── isAuthenticated = true</pre><p>From this point on:</p><ul><li>Every downstream filter</li><li>Every controller</li><li>Every secured method</li></ul><p>Can access the authenticated user.</p><h3>Authorization Filters: Are You Allowed?</h3><p>Authentication answers:</p><blockquote>Who are you?</blockquote><p>Authorization answers:</p><blockquote>Are you allowed to do this?</blockquote><p>Authorization filters check:</p><ul><li>URL patterns</li><li>HTTP methods</li><li>Required roles or authorities</li></ul><p>Example:</p><pre>.requestMatchers(&quot;/admin/**&quot;).hasRole(&quot;ADMIN&quot;)</pre><p>If authorization fails:</p><ul><li>The request is stopped</li><li>A 403 Forbidden response is returned</li></ul><h3>Exception Handling Inside the Filter Chain</h3><p>Spring security has dedicated filters for:</p><ul><li>Authentication failures</li><li>Authorization failures</li></ul><p>These filters:</p><ul><li>Catch security exceptions</li><li>Convert them into proper HTTP responses</li><li>Prevent stack traces from leaking</li></ul><p>This is why Spring Security responses are:</p><ul><li>Predictable</li><li>Consistent</li><li>Standards-compliant</li></ul><h3>When Does the Request Reach the Controller?</h3><p>Only after:</p><ul><li>Authentication succeeds (or is not required)</li><li>Authorization passes</li></ul><p>Then, and only then, the request reaches:</p><pre>DispatcherServlet → Controller</pre><p>At this point:</p><ul><li>The user identity is fully established</li><li>Security is already enforced</li><li>Your controller logic stays clean</li></ul><h3>How Filters and Method Security Work together</h3><p>Filters secure <strong>entry points</strong> (HTTP).</p><p>Method security (via proxies):</p><ul><li>Secures internal method calls</li><li>Adds another layer of defense</li></ul><p>Together they create:</p><blockquote><strong><em>Defense in depth</em></strong></blockquote><h3>Wrap Up</h3><p>The Spring Security filter chain is not magic, it’s <strong>carefully designed pipeline</strong> that:</p><ul><li>Protects your application</li><li>Protects it consistently</li><li>Protects it by default</li></ul><p>Once you understand the flow, Spring Security becomes <strong>predictable, logical and incredibly powerful</strong>.</p><p><em>Follow for more!!!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a624f984a3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Proxies and Filters Exist in Spring Security]]></title>
            <link>https://medium.com/@ayoubtaouam/why-proxies-and-filters-exist-in-spring-security-9854fbc0f168?source=rss-8e17f7fd0be8------2</link>
            <guid isPermaLink="false">https://medium.com/p/9854fbc0f168</guid>
            <category><![CDATA[security-filter-chain]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[proxy]]></category>
            <category><![CDATA[spring-security]]></category>
            <dc:creator><![CDATA[Ayoub Taouam]]></dc:creator>
            <pubDate>Tue, 20 Jan 2026 14:52:21 GMT</pubDate>
            <atom:updated>2026-01-20T14:52:21.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*enzDBwUAUNlrOLcXRgcXsw.png" /></figure><p>If you’ve ever looked into Spring Security internals, you’ve probably encountered concepts like:</p><ul><li>Security filters</li><li>Filter chains</li><li>Proxies</li><li>DelegatingFilterProxy</li><li>Method security proxies</li></ul><p>At first glance, it can feel overwhelming.</p><blockquote>“Why so many layers? Why not just check security in controllers?”</blockquote><p>The short answer is:</p><p><strong>Because security must be centralized, consistent and unavoidable.</strong></p><p>The long answer is what this article is about.</p><h3>The Core Problem: Where Should Security Live?</h3><p>Let’s start with fundamental question, imagine a web application with:</p><ul><li>50 controllers</li><li>200 endpoints</li><li>Multiple authentication methods</li><li>Role-based and attribute-based rules</li></ul><p>Where do you enforce security?</p><h4>Option 1: Inside Controllers</h4><pre>if (!user.isAuthenticated()) {<br>    throw new UnauthorizedException();<br>}</pre><p>Problems:</p><ul><li>Repeated everywhere</li><li>Easy to forget</li><li>Hard to maintain</li><li>Impossible to guarantee consistency</li></ul><p>Security becomes <strong>optional by mistake</strong>.</p><h4>Option 2: Before Requests Reach Your Code</h4><p>This is where <strong>filters </strong>and <strong>proxies </strong>come in.</p><blockquote><strong><em>Spring Security enforces security before your application logic runs.</em></strong></blockquote><p>That’s the key idea.</p><h3>Filters: The Security Checkpoint</h3><h4>Airport Security</h4><p>Before you:</p><ul><li>Board the plane</li><li>Sit in your seat</li><li>Access the cockpit</li></ul><p>You must pass through <strong>security checkpoints</strong>.</p><p>You don’t negotiate with the pilot, you don’t explain yourself to the flight attendant.</p><p>You pass security <strong>before anything else happens</strong>.</p><h4>What Is a Filter?</h4><p>In web applications, a <strong>filter </strong>is a component that:</p><ul><li>Intercepts HTTP requests</li><li>Runs <em>before </em>controllers</li><li>Can stop, modify or allow the request</li></ul><p>In Java web apps, filters at the <strong>Servlet layer</strong>.</p><h4>Why Filters Are Perfect for Security</h4><p>Filters can:</p><ul><li>Read headers</li><li>Read cookies</li><li>Inspect tokens</li><li>Reject requests early</li><li>Attach identity to the request</li></ul><p>Spring Security uses filters to:</p><ul><li>Authenticate users</li><li>Validate tokens</li><li>Restore sessions</li><li>Enforce basic access rules</li></ul><h3>The Spring Security Filter Chain</h3><p>Spring Security doesn’t use <em>one </em>filter. It uses <strong>many specialized filters</strong>, chained together.</p><pre>Request<br>  ↓<br>Security Filter Chain<br>  ├── Authentication Filter<br>  ├── Session Management Filter<br>  ├── CSRF Filter<br>  ├── Authorization Filter<br>  ↓<br>Controller</pre><p>Each filter:</p><ul><li>Does <strong>one job</strong></li><li>Passes control to the next filter</li><li>Can stop the chain if security fails</li></ul><p>The design follows:</p><blockquote><strong><em>Single Responsibility Principle</em></strong></blockquote><h3>Why Not Just One Big Security Filter?</h3><p>Because security is not one concern, it’s many:</p><ul><li>Authentication</li><li>Authorization</li><li>Session handling</li><li>CSRF protection</li><li>Exception handling</li><li>Logout</li><li>Remember-me</li></ul><p>Separating them:</p><ul><li>Improves clarity</li><li>Enables customization</li><li>Makes Spring Security extensible</li></ul><h3>Where Do Proxies Come In?</h3><p>So far, filters protect <strong>HTTP requests</strong>, but what about:</p><ul><li>Service methods</li><li>Business logic</li><li>Background calls</li></ul><p>This is where <strong>proxies </strong>enter the picture.</p><h3>What Is a Proxy?</h3><h4>A Bodyguard</h4><p>You don’t talk directly to a VIP, instead:</p><ul><li>The bodyguard checks who you are</li><li>Decides whether you’re allowed</li><li>Then lets you talk to the VIP</li></ul><p>You never bypass the bodyguard.</p><h4>In Spring</h4><p>A <strong>proxy </strong>is an object that:</p><ul><li>Wraps your real object</li><li>Intercepts method calls</li><li>Adds behavior <em>before or after</em> the method</li></ul><p>Spring Security uses proxies to:</p><ul><li>Enforce method-level security</li><li>Apply annotations like @PreAuthorize</li></ul><h3>Method Security Without Proxies Would Be Impossible</h3><p>Consider this:</p><pre>@PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;)&quot;)<br>public void deleteUser(Long id) {<br>    ...<br>}</pre><p>How does Spring:</p><ul><li>Intercept the method call?</li><li>Evaluate the security expression?</li><li>Block unauthorized access?</li></ul><p>Answer:</p><blockquote><strong><em>A proxy sits between the caller and the real method.</em></strong></blockquote><p>Without proxies:</p><ul><li>The method would be called directly</li><li>Security annotations would be ignored</li></ul><h3>Wrap Up</h3><p>Proxies and filters are not accidental complexity. They are <strong>intentional architectural decisions</strong> that:</p><ul><li>Enforce securiy early</li><li>Enforces scurity everywhere</li><li>Keep your code clean</li><li>Make systems safer by default</li></ul><p>Once you understand this, Spring stops feeling “magical” and starts feeling <strong>inevitable</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9854fbc0f168" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>