<?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 Sasuniwijerathne on Medium]]></title>
        <description><![CDATA[Stories by Sasuniwijerathne on Medium]]></description>
        <link>https://medium.com/@sasuniwijerathne?source=rss-dee57e4a4b9b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-041uVk3T9fBMLA3Tn6LLA.jpeg</url>
            <title>Stories by Sasuniwijerathne on Medium</title>
            <link>https://medium.com/@sasuniwijerathne?source=rss-dee57e4a4b9b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:24:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sasuniwijerathne/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Airport Security Trick That Explains Bloom Filters]]></title>
            <link>https://sasuniwijerathne.medium.com/the-airport-security-trick-that-explains-bloom-filters-d04dafe5f333?source=rss-dee57e4a4b9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d04dafe5f333</guid>
            <category><![CDATA[bloom-filter]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Sasuniwijerathne]]></dc:creator>
            <pubDate>Sat, 14 Mar 2026 18:42:47 GMT</pubDate>
            <atom:updated>2026-03-14T18:42:47.313Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*xn4hg-_vekApwG1doU1NaA.jpeg" /></figure><h3><strong>THE CORE IDEA</strong></h3><h4><strong>The Airport Security Analogy</strong></h4><p>Thousands of passengers pass through a busy international airport every hour. Among them, a few names may appear on a security watchlist — people who require extra screening. Checking every single passenger against the full database would be catastrophically slow.</p><p>So the system uses a clever trick: a super-fast “maybe checker” that can instantly rule out passengers who are definitely not on the watchlist — without ever touching the database.</p><p>This is exactly how a Bloom Filter works.</p><blockquote><strong>KEY INSIGHT </strong>A Bloom Filter doesn’t store names — it stores fingerprints of names as a tiny pattern of bits. Checking membership takes only a few hash operations, making it orders of magnitude faster than a database query.</blockquote><h3><strong>MECHANISM</strong></h3><h4><strong>Step 1 — Prepare the Bit Array</strong></h4><p>The system starts with a bit array — imagine a long row of light switches, all initially set to OFF (0). Multiple hash functions are prepared, each capable of mapping any name to a position in the array.</p><h4><strong>Step 2 — Add Names to the Filter</strong></h4><p>Suppose the name “John Smith” is on the watchlist. The system runs this name through several hash machines, each producing a position number:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qofDHMUNUQVXk3M8LmdkzA.png" /></figure><p>The system flips those three bits to ON. This pattern of lit bits is the fingerprint of “John Smith”. Every watchlist name is processed the same way.</p><h4><strong>Step 3 — Check a Passenger</strong></h4><p>A new passenger arrives — say, Emma Watson. The system runs her name through the same hash functions and gets positions 2, 17, and 31. It then checks those three bits:</p><blockquote><strong>Position 2 </strong>OFF — immediately conclusive. Emma is definitely NOT on the watchlist. No database check required.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sMj1QPNfbO2T8QOMxFGvLQ.png" /></figure><p>She passes through instantly. The Bloom Filter has saved an expensive database lookup by detecting a single OFF bit.</p><h3><strong>DECISION LOGIC</strong></h3><h4><strong>The Two Possible Answers</strong></h4><p>A Bloom Filter can only give two types of answers. There is no third option.</p><blockquote><strong>✓ Definitely NOT present</strong></blockquote><blockquote>At least one bit is OFF, The item is guaranteed not in the set. No database check. Return immediately.</blockquote><blockquote><strong>? Maybe present</strong></blockquote><blockquote>All bits are ON, The item might be in the set. A real database check is needed to confirm.</blockquote><blockquote><strong>CRITICAL GUARANTEE </strong>Bloom Filters never produce false negatives. If an item is in the set, the filter will always say “maybe present”. It may occasionally say “maybe” when the answer is actually “no” — but it never misses a real match.</blockquote><h3><strong>ARCHITECTURE</strong></h3><h4><strong>Request Pipeline — With vs. Without</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3tHGLPw65FbokTIkCjNEw.png" /></figure><h3><strong>PROPERTIES</strong></h3><h4><strong>Why Bloom Filters Are So Efficient</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OHmBYvzczoxl83EVAS_IHQ.png" /></figure><h3><strong>REAL-WORLD APPLICATIONS</strong></h3><h4><strong>Where Bloom Filters Are Used</strong></h4><p>Large-scale production systems rely on Bloom Filters to avoid expensive disk or database lookups. Here are real-world deployments:</p><blockquote><em>Bigtable</em></blockquote><blockquote><em>Cassandra</em></blockquote><blockquote><em>HBase</em></blockquote><blockquote><em>PostgreSQL</em></blockquote><p>These databases use Bloom Filters internally to skip unnecessary disk lookups. When a query arrives for a key that doesn’t exist, the filter catches it instantly — before any disk I/O occurs.</p><blockquote><strong>E-COMMERCE EXAMPLE </strong>When users search for invalid product IDs, every miss without a Bloom Filter hits the cache and then the database. With a filter, non-existent IDs are rejected before any system is touched — blocking thousands of wasteful queries per second.</blockquote><h4><strong>Security Applications</strong></h4><p>Bloom Filters are also used to protect against cache penetration attacks — where malicious actors flood a system with requests for non-existent data specifically to overwhelm the database. The filter acts as the first line of defense, blocking invalid keys instantly.</p><h3><strong>TRADE-OFFS</strong></h3><h4><strong>The Engineering Trade-off</strong></h4><p>Bloom Filters are a brilliant example of deliberately sacrificing perfect accuracy for dramatic gains in performance and memory. Understanding what you give up is essential to using them correctly.</p><h4><strong>What you gain</strong></h4><p>▸ Massive reduction in database load</p><p>▸ Near-zero memory footprint</p><p>▸ Constant-time O(k) lookups</p><p>▸ Protection from cache penetration attacks</p><h4><strong>What you accept</strong></h4><p>▸ Occasional false positives</p><p>▸ Cannot delete items from the filter</p><p>▸ Requires tuning (bit array size, hash count)</p><p>▸ False positive rate grows as items are added</p><p>The false positive rate is controllable. A larger bit array and more hash functions reduce false positives at the cost of more memory. The optimal balance depends on the application’s tolerance for occasional extra database lookups.</p><h3><strong>The Simplest Way to Remember This:</strong></h3><blockquote><strong>Think of it as a bouncer at a club.</strong></blockquote><blockquote>The bouncer doesn’t check the full membership database for every person.Instead, they make a fast call:</blockquote><blockquote><strong>✓ Definitely not on the list ⚠ Maybe on the list — check inside</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d04dafe5f333" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis Caching in Spring Boot — A Complete Beginner Guide with Docker and Real Code Examples]]></title>
            <link>https://sasuniwijerathne.medium.com/redis-caching-in-spring-boot-190c22a3cd33?source=rss-dee57e4a4b9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/190c22a3cd33</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[springboot-3]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Sasuniwijerathne]]></dc:creator>
            <pubDate>Fri, 13 Mar 2026 08:48:35 GMT</pubDate>
            <atom:updated>2026-03-13T08:49:04.852Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jed-UVwaIqf16oq5f8ATDQ.png" /></figure><p>This guide shows you exactly how to add Redis caching to a Spring Boot 3 REST API. You will run Redis in Docker, wire it into Spring Boot, fix real errors like LocalDate serialization and deprecated properties, and verify caching is working from the Redis CLI. All code is from a project I built while learning.</p><h3>What You Will Learn</h3><p>This is not a theoretical overview of Redis. Every section comes from a real problem I ran into while adding caching to my Spring Boot Event Management API. By the end you will know how to:</p><p>• Understand what Redis is and why it makes APIs faster</p><p>• Run a Redis instance locally using Docker in one command</p><p>• Add Redis caching to a Spring Boot 3 REST API</p><p>• Fix the deprecated spring.redis.host property in Spring Boot 3.x</p><p>• Handle LocalDate and LocalDateTime serialization in Redis</p><p>• Use @Cacheable, @CacheEvict, and RedisCacheManager correctly</p><p>• Verify that Redis is actually caching your data using the Redis CLI</p><p><strong>Prerequisites: </strong>You should know Java and Spring Boot basics. No Redis experience needed.</p><h3>What is Redis?</h3><p>Redis stands for Remote Dictionary Server. It is an open-source, in-memory key-value database. Unlike MySQL which stores data on disk, Redis keeps everything in RAM. That one difference makes it dramatically faster for reads.</p><p>The simplest mental model: imagine your Spring Boot app has a very fast sticky note pad sitting next to it. Instead of walking to the filing room (MySQL) every single time someone asks the same question, you check the sticky note first. If the answer is already written there, you hand it back instantly. If not, you go to the filing room, get the answer, write it on the sticky note for next time, and return it. That is caching.</p><h3>Redis vs MySQL at a glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHcLuhJxx30fbcS77yNgCQ.png" /></figure><p>Big companies like Netflix, Uber, Twitter, and GitHub all use Redis in production. The reason is the same one you are reading this article for — when thousands of users request the same data, hitting the database every single time is wasteful and slow.</p><h3>Step 1 — Run Redis with Docker</h3><p>The fastest way to get Redis running locally is Docker. If you have Docker installed, one command is all you need.</p><h4>Pull and start Redis</h4><pre>docker pull redis<br>docker run -d -p 6379:6379 - name redis-server redis</pre><p>The <em>-p 6379:6379</em> flag maps your machine’s port 6379 to the container’s port <em>6379</em>. The -d flag runs it in the background.</p><h4>Common error: port already allocated</h4><p>If you see this error:</p><pre>Bind for 0.0.0.0:6379 failed: port is already allocated</pre><p>It means another Redis container is already using port 6379. Here is the fix:</p><pre>docker ps -a<br>docker stop &lt;old-container-name&gt;<br>docker rm &lt;old-container-name&gt;<br>docker run -d -p 6380:6379 - name redis redis</pre><p>Now Redis runs on host port <em>6380</em>. You will reference this port in your Spring Boot config.</p><h3>Verify Redis is working</h3><pre>docker exec -it redis redis-cli<br>SET name &quot;SpringBoot&quot;<br>GET name<br># Output: &quot;SpringBoot&quot;</pre><p>If you see your value returned, Redis is running correctly.</p><h3>Useful Docker commands for Redis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSiFS43jxEKKU6BFhDKOWg.png" /></figure><h3>Step 2 — Add Dependencies to pom.xml</h3><p>You need three dependencies. The first two enable Redis caching in Spring Boot. The third fixes a LocalDate serialization error that will stop your app from starting if your DTOs contain Java 8 date types.</p><pre>&lt;dependency&gt;<br>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>&lt;artifactId&gt;spring-boot-starter-data-redis&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br><br>&lt;dependency&gt;<br>&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>&lt;artifactId&gt;spring-boot-starter-cache&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br><br>&lt;! - Required if your DTOs use LocalDate or LocalDateTime →<br>&lt;dependency&gt;<br>&lt;groupId&gt;com.fasterxml.jackson.datatype&lt;/groupId&gt;<br>&lt;artifactId&gt;jackson-datatype-jsr310&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><h4><strong>Why jackson-datatype-jsr310?</strong></h4><p>Without this dependency, Jackson (the JSON library Spring Boot uses) cannot serialize LocalDate or LocalDateTime fields. You will get the error: <strong><em>“Java 8 date/time type java.time.LocalDate not supported by default.”</em></strong> Adding this module and annotating your DTO fields with @JsonFormat fixes it completely.</p><h3>Step 3 — Configure Redis in application.properties</h3><p>Spring Boot 3.x deprecated the old properties spring.redis.host and spring.redis.port. If you use them you will see a yellow warning in your console. The correct approach in Spring Boot 3 is to use the URL format:</p><pre># Spring Boot 3.x - correct way<br>spring.redis.url=redis://localhost:6380<br>spring.redis.username=<br>spring.redis.password=</pre><h4><strong>Deprecated in Spring Boot 3.x</strong></h4><p><em>Do not use spring.redis.host=localhost or spring.redis.port=6379. These are deprecated and will be removed in a future release. Always use spring.redis.url=redis://host:port instead.</em></p><h3>Step 4 — Enable Caching in Your Main Class</h3><p>Add the @EnableCaching annotation to your main application class. Without this, Spring Boot will ignore all your @Cacheable annotations silently.</p><pre>@SpringBootApplication<br>@EnableCaching<br>public class Application {<br>  public static void main(String[] args) {<br>    SpringApplication.run(Application.class, args);<br>  }<br>}</pre><h3>Step 5 — RedisConfig with JSON Serialization</h3><p>This is the most important configuration step that most beginner tutorials skip. By default, Redis uses binary Java serialization. This causes two problems:</p><p>• Cached data is unreadable in the Redis CLI — you see garbled bytes instead of JSON</p><p>• If you change your DTO structure and Redis still holds the old binary object, you get a ClassCastException or deserialization error</p><p>The solution is to configure GenericJackson2JsonRedisSerializer so all cached objects are stored as readable JSON:</p><pre>@Configuration<br>@EnableCaching<br>public class RedisConfig {<br>   @Bean<br>    public RedisCacheManager cacheManager(RedisConnectionFactory factory) {<br>       RedisCacheConfiguration config = RedisCacheConfiguration<br>       .defaultCacheConfig()<br>       .serializeValuesWith(<br><br>      RedisSerializationContext.SerializationPair.fromSerializer(<br>         new GenericJackson2JsonRedisSerializer()<br>       )<br>   )<br>   .entryTtl(Duration.ofMinutes(10)) // cache expires after 10 minutes<br>   .disableCachingNullValues();<br> return RedisCacheManager.builder(factory)<br>   .cacheDefaults(config)<br>   .build();<br> }<br>}</pre><p>The entryTtl(Duration.ofMinutes(10)) line sets a time-to-live on cached data. After 10 minutes, the cache automatically expires and the next request fetches fresh data from the database. This is important for production — without it, stale data lives in Redis forever.</p><h3>Step 6 — Fix LocalDate in Your DTO</h3><p>If your DTO has LocalDate or LocalDateTime fields, you need to annotate them so Jackson knows how to format them:</p><pre>@AllArgsConstructor<br>@NoArgsConstructor<br>@Getter<br>@Setter<br>public class EventDTO {<br>  private Integer id;<br>  private String eventName;<br><br>  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = &quot;yyyy-MM-dd&quot;)<br>  private LocalDate eventDate;<br><br>  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = &quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss&quot;)<br>  private LocalDateTime eventBooked;<br><br>  private String eventLocation;<br>  private String eventDescription;<br>  private String eventStatus;<br>}</pre><p>Without @JsonFormat, dates serialize as a raw timestamp number, which cannot be deserialized back from Redis. With it, eventDate becomes “2026–03–13” and eventBooked becomes “2026–03–13T14:30:00” — clean, readable, and safe.</p><h3>Step 7 — The Three Caching Annotations</h3><h4>@Cacheable — for read operations</h4><p>Put this on any method that fetches data. The first call executes the method and stores the result in Redis. Every subsequent call with the same parameters returns the cached result without touching the database.</p><pre>@Cacheable(&quot;events&quot;)<br>public List&lt;EventDTO&gt; getAllEvents() {<br>  System.out.println(&quot;Fetching from database…&quot;); // only prints on first call<br>  List&lt;Event&gt; events = eventRepository.findAll();<br>  return modelMapper.map(events, new TypeToken&lt;List&lt;EventDTO&gt;&gt;() {}.getType());<br>}</pre><p>How to confirm it is working: call your endpoint twice. The first call prints the console message. The second call is silent — Redis served it.</p><h4>@CacheEvict — for write operations</h4><p>When data changes, the cached version becomes stale. @CacheEvict removes it from Redis so the next GET fetches fresh data from the database.</p><pre>@CacheEvict(value = &quot;events&quot;, allEntries = true)<br>public void saveEvent(EventDTO dto) {<br>  eventRepository.save(modelMapper.map(dto, Event.class));<br>}</pre><h4>@CachePut — for update operations</h4><p>Updates the cache with a new value after a write without removing the existing entry first. Less common but useful when you want the cache to always reflect the latest value immediately after an update.</p><h3>Step 8 — The Full Controller</h3><p>Here is the complete EventController from my project, with all caching annotations in place:</p><pre>@RestController<br>@RequestMapping(&quot;api/v1/event&quot;)<br>@RequiredArgsConstructor<br>public class EventController {<br>private final EventService eventService;<br><br>  @PostMapping(&quot;create&quot;)<br>  @CacheEvict(value = &quot;events&quot;, allEntries = true)<br>  public ResponseEntity&lt;APIResponse&gt; saveEvent(@Valid @RequestBody EventDTO dto) {<br>    eventService.saveEvent(dto);<br>    return ResponseEntity.ok(new APIResponse(200, &quot;Success&quot;, &quot;Event created&quot;));<br>  }<br><br>  @GetMapping(&quot;all&quot;)<br>  @Cacheable(&quot;events&quot;)<br>  public ResponseEntity&lt;APIResponse&gt; getAllEvents() {<br>    List&lt;EventDTO&gt; dtos = eventService.getAllEvents();<br>    return ResponseEntity.ok(new APIResponse(200, &quot;Success&quot;, dtos));<br>  }<br><br>  @PutMapping(&quot;update&quot;)<br>  @CacheEvict(value = &quot;events&quot;, allEntries = true)<br>  public ResponseEntity&lt;APIResponse&gt; updateEvent(@Valid @RequestBody EventDTO dto) {<br>    eventService.updateEvent(dto);<br>    return ResponseEntity.ok(new APIResponse(200, &quot;Success&quot;, &quot;Event updated&quot;));<br>  }<br><br>  @PatchMapping(&quot;status/{id}&quot;)<br>  @CacheEvict(value = &quot;events&quot;, allEntries = true)<br>  public ResponseEntity&lt;APIResponse&gt; changeStatus(@PathVariable String id) {<br>    eventService.changeEventStatus(id);<br>    return ResponseEntity.ok(new APIResponse(200, &quot;Success&quot;, &quot;Status changed&quot;));<br>  }<br><br>  @GetMapping(&quot;search/{keyword}&quot;)<br>  public ResponseEntity&lt;APIResponse&gt; searchEvent(@PathVariable String keyword) {<br>    List&lt;Event&gt; events = eventService.searchEvent(keyword);<br>    return ResponseEntity.ok(new APIResponse(200, &quot;Success&quot;, events));<br>  }<br><br>  @GetMapping<br>  public ResponseEntity&lt;Page&lt;Event&gt;&gt; getEvents(<br>  @RequestParam(defaultValue = &quot;0&quot;) int page,<br>  @RequestParam(defaultValue = &quot;5&quot;) int size) {<br>    return ResponseEntity.ok(eventService.getEvents(page, size));<br>  }<br> }</pre><p>Notice that search and pagination are not cached. Keyword searches have too many possible inputs to cache effectively. Pagination is better left uncached because pages change as records are added or removed.</p><h3>Step 9 — Verify Redis is Actually Caching</h3><p>This is the step most tutorials miss. Here is how to confirm Redis is caching your data with your own eyes.</p><p>1. Start Redis and run your Spring Boot app</p><p>2. Call your GET endpoint in Postman — note the console prints the database message</p><p>3. Call the same endpoint again — the console should be silent</p><p>4. Now open the Redis CLI:</p><pre>docker exec -it redis redis-cli<br>KEYS *<br># You should see something like:<br># 1) &quot;events::SimpleKey []&quot;</pre><p>5. Read the cached JSON:</p><pre>GET &quot;events::SimpleKey []&quot;<br># Returns your events as JSON stored in Redis</pre><p>6. Call a POST or PUT endpoint, then run KEYS * again — the key is gone (evicted)</p><p>7. Call GET again — the key reappears as the cache rebuilds from the database</p><h4><strong>Getting a deserialization error after changing your DTO?</strong></h4><p><em>This happens when Redis still holds a cached version of your old DTO structure. The fix is simple: open redis-cli and run FLUSHALL. This clears everything and lets the cache rebuild cleanly on the next request. Always do this after changing DTO fields or serialization settings.</em></p><p><em>Figure 1: Redis caching flow — cache hit path (green), cache miss path (orange), and cache eviction on write operations (black)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IJph313sifJoyAbesM3TYQ.png" /><figcaption>Figure 1: Redis caching flow — cache hit path (green), cache miss path (orange), and cache eviction on write operations (black)</figcaption></figure><h3>How the Cache Flow Works</h3><p>Here is a summary of what happens on every request after caching is set up:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sr_zEHIcath3sbz10JytA.png" /></figure><h3>Common Errors and Fixes</h3><h4>1. Deprecated property warning</h4><pre># Wrong (Spring Boot 3.x deprecated):<br>spring.redis.host=localhost<br>spring.redis.port=6379<br># Correct:<br>spring.redis.url=redis://localhost:6380</pre><h4>2. LocalDate serialization error</h4><pre># Error:<br>Java 8 date/time type java.time.LocalDate not supported by default<br># Fix: add to pom.xml<br>&lt;artifactId&gt;jackson-datatype-jsr310&lt;/artifactId&gt;<br># And annotate DTO fields:<br>@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = &quot;yyyy-MM-dd&quot;)<br>private LocalDate eventDate;</pre><h4>3. Port already allocated</h4><pre># Error:<br>Bind for 0.0.0.0:6379 failed: port is already allocated<br># Fix:<br>docker stop old-container-name<br>docker rm old-container-name<br>docker run -d -p 6380:6379 - name redis redis</pre><h4>4. ClassCastException from Redis</h4><pre># Cause: old binary-serialized data in Redis<br># Fix: clear the cache<br>docker exec -it redis redis-cli<br>FLUSHALL</pre><h3>Key Takeaways</h3><p>• Redis is an in-memory key-value store. It is fast because it reads from RAM, not disk.</p><p>• In Spring Boot 3.x, use spring.redis.url instead of the deprecated spring.redis.host and spring.redis.port.</p><p>• Always configure GenericJackson2JsonRedisSerializer. Binary serialization causes hard-to-debug errors when DTOs change.</p><p>• Add jackson-datatype-jsr310 to pom.xml whenever your DTOs have LocalDate or LocalDateTime fields.</p><p>• @Cacheable goes on read methods. @CacheEvict goes on write, update, and delete methods.</p><p>• Set a TTL on your cache manager (entryTtl) so stale data does not live in Redis forever.</p><p>• After any DTO change, run FLUSHALL in redis-cli to clear stale binary data.</p><p>• Use KEYS * in redis-cli to confirm your data is actually being cached.</p><h3>Final Thoughts</h3><p>A week ago I had zero knowledge of Redis. Working through a real project — with real errors, real Docker commands, and a real Spring Boot API — made it click faster than any course could.</p><p>The concept is genuinely simple: check fast storage first, fall back to slow storage only when needed. The Spring Boot annotations make the implementation just as simple. Once you wire it up, you can see the difference immediately in your console logs — the database query disappears on the second call and every call after.</p><p>If you are building Spring Boot APIs and you have not added caching yet, this is the right time to start. Add @Cacheable to one endpoint, run your app, and watch the console. Seeing it work for the first time makes the whole concept stick.</p><blockquote>Written while learning Spring Boot</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=190c22a3cd33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing Spring Boot Applications: The Complete Guide]]></title>
            <link>https://sasuniwijerathne.medium.com/dockerizing-spring-boot-applications-the-complete-guide-ef58f688e275?source=rss-dee57e4a4b9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef58f688e275</guid>
            <dc:creator><![CDATA[Sasuniwijerathne]]></dc:creator>
            <pubDate>Fri, 13 Feb 2026 14:57:28 GMT</pubDate>
            <atom:updated>2026-02-13T14:57:28.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*h7RZAORyZODuSKd_BO7z4Q.jpeg" /></figure><h3>Introduction</h3><p>Docker has revolutionized modern software development by enabling developers to “build, share, and run containerized applications for other developers of all skill levels.” For Spring Boot applications, containerization provides consistency across development, testing, and production environments, simplified deployment, and efficient resource utilization. This comprehensive guide covers everything from fundamental concepts to advanced production deployments, real-world examples, and interview preparation.</p><h3>What is Docker?</h3><p>Docker is an open platform for developing, shipping, and running applications in containers. A container bundles an application’s code together with all its runtime dependencies (libraries, system tools, configuration) so it can run quickly and reliably in any environment.</p><p><strong>Key Differences: Containers vs Virtual Machines</strong></p><p>Unlike virtual machines, Docker containers share the host OS kernel and are extremely lightweight, enabling rapid startup and efficient resource usage. This fundamental difference makes containers ideal for microservices architectures and cloud-native applications.</p><h3>Core Docker Concepts</h3><h4>Images vs Containers</h4><ul><li><strong>Docker Image</strong>: A read-only template that includes application code and environment. Think of it as a “lightweight, standalone, executable package that includes everything needed to run software.”</li><li><strong>Docker Container</strong>: A running instance of that image, with its own writable filesystem.</li></ul><p><strong>In short: image = template, container = process.</strong></p><h4>Dockerfile</h4><p>A Dockerfile is a plain-text recipe for building a Docker image. It contains sequential instructions (like FROM, COPY, RUN, CMD) that define how to construct the image layer by layer. Each instruction creates a new image layer, which makes builds incremental and efficient.</p><p>Example structure:</p><pre>FROM openjdk:17-jdk-slim      # Base image<br>COPY target/*.jar app.jar     # Copy application<br>ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;]  # Run command</pre><h4>Docker Compose</h4><p>Docker Compose is a tool for defining and running multi-container Docker applications. A docker-compose.yml file describes a set of services (e.g., a Spring Boot app, a database, a message broker), their images or build contexts, networks, volumes, and environment variables.</p><p><strong>Think of it this way:</strong></p><ul><li><strong>Dockerfile</strong>: Recipe for building a single image</li><li><strong>Docker Compose</strong>: Menu for running multiple containers together</li></ul><p>Compose acts like a “dinner menu” for Docker: it lets you declare one container for the backend (built from your Dockerfile), one container for the database, one for caching or messaging, etc. Then a single command (docker compose up) launches the entire stack exactly as specified.</p><h3>Why Dockerize Spring Boot Applications?</h3><p>Containerizing Spring Boot applications yields several critical benefits:</p><p><strong>1. Consistency and Portability</strong></p><p>As Docker’s documentation notes, running a Spring Boot app in a container means “developers can install their app from a single package and get it up and running in minutes,” with guaranteed environment consistency across dev/test/production.</p><p><strong>2. Environment Abstraction</strong></p><p>Docker abstracts away JVM or OS differences. You dockerize a Java app the same way as any other language, so each service behaves identically everywhere.</p><p><strong>3. Elimination of “Works on My Machine”</strong></p><p>No more dependency conflicts or environment-specific bugs. Common benefits include:</p><ul><li>Easy scaling (e.g., replicate a container in Kubernetes)</li><li>Quicker CI/CD pipelines (build-once-run-anywhere)</li><li>Isolation of dependencies</li></ul><h3>Dockerizing a Spring Boot Application</h3><h4>Step 1: Package the Application</h4><p>Use Maven or Gradle to build an executable JAR. For Maven, include the Spring Boot plugin in pom.xml:</p><pre>&lt;build&gt;<br>  &lt;plugins&gt;<br>    &lt;plugin&gt;<br>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>      &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;<br>    &lt;/plugin&gt;<br>  &lt;/plugins&gt;<br>&lt;/build&gt;</pre><p>Then run:</p><pre>mvn clean package<br># or<br>./mvnw clean package</pre><p>The fat JAR (e.g., app.jar) will be created in target/.</p><h4>Step 2: Write a Dockerfile</h4><p>Create a file named Dockerfile in the project root (no file extension). A simple Dockerfile for a Spring Boot JAR:</p><pre>FROM openjdk:17-jdk-slim<br>VOLUME /tmp<br>ARG JAR_FILE=target/*.jar<br>COPY ${JAR_FILE} app.jar<br>ENTRYPOINT [&quot;java&quot;,&quot;-jar&quot;,&quot;/app.jar&quot;]</pre><p><strong>Explanation:</strong></p><ul><li>FROM openjdk:17-jdk-slim: Selects a base image (slim OpenJDK 17) to minimize size</li><li>VOLUME /tmp: Optional but can improve performance on some platforms</li><li>ARG JAR_FILE and COPY: Copy the built JAR from Maven&#39;s target folder into the container</li><li>ENTRYPOINT: Sets the default command to run the Spring Boot app when the container starts</li></ul><p><strong>Important</strong>: Each line of the Dockerfile creates an image layer. Best practices include using uppercase instructions and a .dockerignore to exclude local files (e.g., /target, .git) from the build context to speed up builds and avoid bloating the image.</p><h4>Step 3: Build the Docker Image</h4><pre>docker build -t my-spring-app:latest .</pre><p>This uses the Dockerfile in the current directory (.) to build an image tagged my-spring-app:latest. The -t flag specifies the image name and tag. Docker will execute each Dockerfile step, caching layers so that unchanged steps are skipped on rebuild (which makes iterative builds faster).</p><h4>Step 4: Run the Docker Container</h4><pre>docker run -p 8080:8080 my-spring-app:latest</pre><p>This maps port 8080 of the host to port 8080 in the container, so the Spring Boot application (which by default listens on 8080) is accessible via http://localhost:8080 on the host. The container runs the entrypoint command defined in the Dockerfile.</p><p><strong>At this point, your Spring Boot service is running in Docker exactly as it would as a standalone JAR — but now it’s isolated, with its own filesystem and environment.</strong></p><h4>Step 5: (Optional) Use Spring Boot Maven Plugin for Images</h4><p>Recent Spring Boot releases include a spring-boot:build-image goal:</p><pre>mvn spring-boot:build-image</pre><p>This uses Cloud Native Buildpacks to create OCI images. This automates some steps, but under the hood it still produces a Docker image that you can run. You can explore that as an alternative to a manual Dockerfile, especially if you prefer buildpack conventions.</p><h3>Managing Services with Docker Compose</h3><p>For microservice setups or when your Spring Boot app needs supporting services (databases, caches, message brokers), Docker Compose can orchestrate everything.</p><h4>Complete Docker Compose Example</h4><p>Create a docker-compose.yml that defines all services:</p><pre>version: &#39;3.8&#39;<br>services:<br>  app:<br>    build: .<br>    ports:<br>      - &quot;8080:8080&quot;<br>    depends_on:<br>      - db<br>      - rabbitmq<br>    environment:<br>      SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/mydb<br>      SPRING_DATASOURCE_USERNAME: user<br>      SPRING_DATASOURCE_PASSWORD: password<br>      SPRING_RABBITMQ_HOST: rabbitmq</pre><pre>  db:<br>    image: postgres:13<br>    environment:<br>      POSTGRES_DB: mydb<br>      POSTGRES_USER: user<br>      POSTGRES_PASSWORD: password<br>    ports:<br>      - &quot;5432:5432&quot;</pre><pre>  rabbitmq:<br>    image: rabbitmq:3-management<br>    ports:<br>      - &quot;5672:5672&quot;<br>      - &quot;15672:15672&quot;</pre><p><strong>Service Breakdown:</strong></p><ul><li><strong>app service</strong>: Built from the local Dockerfile (build: .), with port mapping and environment variables that Spring Boot reads (e.g., JDBC URL and credentials) to connect to the db service, and a SPRING_RABBITMQ_HOST pointing to the rabbitmq service.</li><li><strong>db service</strong>: Uses the official PostgreSQL image, sets up a database via environment variables, and exposes its port.</li><li><strong>rabbitmq service</strong>: Runs RabbitMQ with management UI, exposing the default AMQP and UI ports.</li></ul><p>With this file, running docker-compose up --build will start all three containers, creating a default Docker network for them. The Spring Boot app container can reach db and rabbitmq by their service names (DNS provided by Compose).</p><p>Using depends_on ensures the DB and RabbitMQ start before the app tries to connect. This setup exemplifies how Docker Compose simplifies multi-service orchestration for Spring Boot microservices.</p><h3>Common Interview Questions and Answers</h3><h4>Q1: What is the difference between a Docker image and a Docker container?</h4><p><strong>Answer:</strong> A Docker image is a static, build-time artifact — “a lightweight, standalone, executable package that includes everything needed to run software.” It’s a read-only template containing the application code and all its dependencies.</p><p>A container is a running instance of that image, with its own writable filesystem. Think of it this way: <strong>image = template, container = process.</strong></p><p>For example, you might have one spring-boot-app:1.0 image but run multiple containers from it, each serving different requests.</p><h4>Q2: Why containerize Spring Boot applications?</h4><p><strong>Answer:</strong> Containerizing Spring Boot applications provides several key benefits:</p><ol><li><strong>Consistency and Portability</strong>: As Docker’s documentation notes, running a Spring Boot app in a container means “developers can install their app from a single package and get it up and running in minutes,” with guaranteed environment consistency across dev/test/production.</li><li><strong>No More “Works on My Machine”</strong>: Docker abstracts away JVM or OS differences, ensuring identical behavior everywhere.</li><li><strong>Microservices Enablement</strong>: Containers allow easy scaling, independent deployment, and service isolation.</li><li><strong>Faster CI/CD</strong>: Build-once-run-anywhere accelerates deployment pipelines.</li><li><strong>Resource Efficiency</strong>: Containers share the host OS kernel, making them more lightweight than VMs.</li></ol><h4>Q3: What’s the difference between a Dockerfile and Docker Compose?</h4><p><strong>Answer:</strong> Think of it with the “recipe vs. menu” analogy:</p><ul><li><strong>Dockerfile</strong>: A recipe for building a <strong>single</strong> Docker image. It defines how to construct an image layer by layer using instructions like FROM, COPY, RUN, CMD.</li><li><strong>Docker Compose</strong>: A menu for running <strong>multiple</strong> containers together. A docker-compose.yml file describes a set of services (e.g., app, database, cache), their configurations, networks, and volumes.</li></ul><p>In practice: Use a Dockerfile to build an image, and use Docker Compose to run a group of containers together as a complete application stack.</p><h4>Q4: Explain the key instructions in a Dockerfile</h4><p><strong>Answer:</strong></p><ul><li><strong>FROM</strong>: Specifies the base image (e.g., FROM openjdk:17-jdk-slim)</li><li><strong>COPY</strong>: Copies files from host to container (preferred for simple file copies)</li><li><strong>ADD</strong>: Similar to COPY but with extra features (can extract archives, download URLs) — use COPY when possible</li><li><strong>RUN</strong>: Executes commands during image build (e.g., RUN apt-get update)</li><li><strong>WORKDIR</strong>: Sets working directory for subsequent instructions</li><li><strong>EXPOSE</strong>: Documents which ports the container listens on (informational only)</li><li><strong>ENV</strong>: Sets environment variables</li><li><strong>ENTRYPOINT</strong>: Defines the main executable (cannot be overridden easily)</li><li><strong>CMD</strong>: Provides default arguments to ENTRYPOINT or default command (can be overridden)</li></ul><p><strong>Important</strong>: Each instruction creates a new image layer, which is why ordering and layer caching matter for build performance.</p><h4>Q5: What’s the difference between ENTRYPOINT and CMD?</h4><p><strong>Answer:</strong></p><ul><li><strong>ENTRYPOINT</strong>: Sets the main command that always runs. It’s harder to override.</li><li><strong>CMD</strong>: Provides default arguments to ENTRYPOINT or a default command that can be easily overridden.</li></ul><p><strong>Best practice</strong>: Combine them for flexibility:</p><pre>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;]<br>CMD [&quot;app.jar&quot;]</pre><p>This allows users to override the JAR file name but keeps the java -jar execution fixed.</p><p>Alternatively:</p><pre>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p>This fixes everything and is common for single-purpose containers.</p><h4>Q6: How do you handle different environments (dev, test, prod) with Docker?</h4><p><strong>Answer:</strong> The best approach is to externalize configuration using Spring profiles and environment variables:</p><ol><li><strong>Spring Profiles</strong>: Use SPRING_PROFILES_ACTIVE environment variable:</li></ol><pre>docker run -e SPRING_PROFILES_ACTIVE=prod my-app</pre><ol><li><strong>Environment Variables</strong>: Pass configuration at runtime:</li></ol><pre># docker-compose.yml<br>environment:<br>  SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/mydb<br>  SPRING_DATASOURCE_USERNAME: ${DB_USER}<br>  SPRING_DATASOURCE_PASSWORD: ${DB_PASSWORD}</pre><ol><li><strong>External Configuration</strong>: Mount configuration files as volumes:</li></ol><pre>docker run -v ./config:/config -e SPRING_CONFIG_LOCATION=/config/ my-app</pre><p>This follows 12-factor app principles and keeps images environment-agnostic.</p><h4>Q7: How would you reduce Docker image size?</h4><p><strong>Answer:</strong> Several strategies:</p><ol><li><strong>Use Smaller Base Images</strong>: Switch from full JDK to JRE, and use Alpine-based images:</li></ol><pre>FROM eclipse-temurin:17-jre-alpine  # ~150MB vs 500+ MB</pre><ol><li><strong>Multi-Stage Builds</strong>: Separate build and runtime:</li></ol><pre>FROM maven:3.9-jdk-17 AS builder<br># ... build here ...</pre><pre>FROM eclipse-temurin:17-jre-alpine<br>COPY --from=builder /app/target/*.jar app.jar</pre><ol><li><strong>Layered JARs</strong>: Enable in Spring Boot to cache dependencies separately:</li></ol><pre>&lt;layers&gt;<br>  &lt;enabled&gt;true&lt;/enabled&gt;<br>&lt;/layers&gt;</pre><ol><li><strong>Use .dockerignore</strong>: Exclude unnecessary files from build context</li><li><strong>Remove Build Tools</strong>: Don’t include Maven/Gradle in runtime image</li><li><strong>Minimize Layers</strong>: Combine RUN commands where appropriate</li></ol><p>Result: Image size can be reduced by 60–80% compared to naive builds.</p><h4>Q8: What are Docker volumes and why use them?</h4><p><strong>Answer:</strong> By default, changes in a container are ephemeral. As Docker documentation notes, when a container is removed, any data not in a mounted volume disappears.</p><p><strong>Docker volumes</strong> provide persistent storage that survives container restarts and removals.</p><p>Use cases:</p><ul><li>Database data storage</li><li>Application logs</li><li>Shared data between containers</li></ul><p>Example:</p><pre>volumes:<br>  postgres_data:</pre><pre>services:<br>  db:<br>    image: postgres:13<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data</pre><p>This ensures database data persists even if the container is recreated.</p><h4>Q9: Explain Docker networking in the context of microservices</h4><p><strong>Answer:</strong> Docker Compose automatically creates an isolated network for services, enabling them to communicate using service names as hostnames.</p><p>Example:</p><pre>services:<br>  app:<br>    environment:<br>      DATABASE_URL: jdbc:postgresql://db:5432/mydb  # &#39;db&#39; is the service name<br>  <br>  db:<br>    image: postgres:13</pre><p>The app service can reach the database at hostname db because Compose provides DNS resolution.</p><p><strong>For production</strong>: Orchestrators like Kubernetes use Services and Ingress for more sophisticated networking, including load balancing, service discovery, and external access control.</p><h4>Q10: How do you integrate Docker into a CI/CD pipeline?</h4><p><strong>Answer:</strong> A typical CI/CD flow:</p><p><strong>Build Phase</strong>:</p><ul><li>Pull code from repository</li><li>Run tests (mvn test)</li><li>Build JAR (mvn package)</li><li>Build Docker image (docker build)</li><li>Tag with version/commit SHA</li></ul><p><strong>Push Phase</strong>:</p><ul><li>Push to container registry (Docker Hub, ECR, GCR)</li><li>Scan for vulnerabilities (Trivy, Snyk)</li></ul><p><strong>Deploy Phase</strong>:</p><ul><li>Pull image to servers</li><li>Update Kubernetes deployments or Docker Compose</li><li>Perform rolling updates</li><li>Run health checks</li></ul><p>Example with GitHub Actions:</p><pre>- name: Build with Maven<br>  run: mvn clean package<br>  <br>- name: Build Docker image<br>  run: docker build -t myapp:${{ github.sha }} .<br>  <br>- name: Push to registry<br>  run: docker push myapp:${{ github.sha }}<br>  <br>- name: Deploy to Kubernetes<br>  run: kubectl set image deployment/myapp myapp=myapp:${{ github.sha }}</pre><h4>Q11: Describe a real-world microservices deployment scenario</h4><p><strong>Answer:</strong> “In our e-commerce platform, we deployed multiple Spring Boot microservices using Docker and Kubernetes:</p><p><strong>Architecture:</strong></p><ul><li><strong>API Gateway</strong>: Routes requests, handles authentication</li><li><strong>Product Service</strong>: Manages product catalog (with PostgreSQL)</li><li><strong>Order Service</strong>: Processes orders (with MySQL)</li><li><strong>User Service</strong>: User management and profiles</li><li><strong>Notification Service</strong>: Email/SMS notifications (with RabbitMQ)</li><li><strong>Eureka Server</strong>: Service discovery</li></ul><p><strong>Deployment:</strong></p><ul><li>Each service in its own Docker container</li><li>Kubernetes for orchestration (3 replicas per service)</li><li>Horizontal Pod Autoscaling based on CPU/memory</li><li>PostgreSQL and MySQL as StatefulSets</li><li>RabbitMQ for async messaging</li><li>Prometheus and Grafana for monitoring</li><li>Health checks via Spring Boot Actuator</li><li>Rolling updates with zero downtime</li></ul><p><strong>Benefits:</strong></p><ul><li>Independent scaling of services</li><li>Easy rollback with image versions</li><li>Consistent environments across dev/test/prod</li><li>Fast deployments (2–3 minutes)</li><li>Automatic recovery from failures”</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef58f688e275" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monolithic vs Microservices: Which One Should You Choose?]]></title>
            <link>https://sasuniwijerathne.medium.com/monolithic-vs-microservices-which-one-should-you-choose-521384f41286?source=rss-dee57e4a4b9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/521384f41286</guid>
            <dc:creator><![CDATA[Sasuniwijerathne]]></dc:creator>
            <pubDate>Tue, 09 Dec 2025 15:14:19 GMT</pubDate>
            <atom:updated>2025-12-09T15:14:19.409Z</atom:updated>
            <content:encoded><![CDATA[<p>As a computer science undergraduate, I still remember the first time I built a <strong>Java web application</strong> for my <strong>2nd semester final project</strong> a <strong>Blog Management System</strong>. The system allowed users to create, edit, and delete blog posts, manage comments, and categorize articles. I wrote all the code in a single Java project using <strong>Spring Boot: </strong>controllers, services, repositories, everything in one place. This was my <strong>first monolithic application</strong>.</p><p>At the beginning, it worked perfectly. I could run the app locally, test all features, and deploy it as a single .jar file. But as soon as I added new features like <strong>user authentication</strong>, <strong>tag management</strong>, and <strong>analytics dashboards</strong>, the code became messy. Changing one module often broke another. Deployments were risky, and scaling was almost impossible. That’s when I learned about <strong>microservices</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_oPW7peuSSdz1PvCiav57g.png" /></figure><h3>What is a Monolithic Architecture?</h3><p>A <strong>monolithic application</strong> is a single, unified codebase where all components are tightly coupled. Everything business logic, database access, and user interface lives together.</p><p><strong>Example in Java (Spring Boot Monolith):</strong></p><pre>@RestController<br>@RequiedArgsConstructor<br>public class BlogController {<br><br>    private final PostService postService;<br>    private final CommentService commentService;<br><br>    @PostMapping(&quot;/post&quot;)<br>    public String createPost(@RequestBody Post post) {<br>        postService.addPost(post);<br>        commentService.initializeComments(post);<br>        return &quot;Post created successfully!&quot;;<br>    }<br>}</pre><p>In this example, BlogController directly interacts with multiple services. It’s simple to start but <strong>difficult to scale or maintain</strong> as the project grows.</p><p><strong>Pros of Monoliths:</strong></p><ul><li>Easy to develop for small projects.</li><li>Simple deployment (single unit).</li><li>Easier for beginners to understand.</li></ul><p><strong>Cons of Monoliths:</strong></p><ul><li>Hard to scale specific modules.</li><li>Large codebase becomes unmanageable.</li><li>Risk of breaking the whole system with small changes.</li></ul><h3>What are Microservices?</h3><p><strong>Microservices architecture</strong> breaks the application into <strong>smaller, independent services</strong>, each responsible for a single functionality. Each service can be developed, deployed, and scaled independently.</p><p><strong>Example in Java (Spring Boot Microservice for Posts):</strong></p><pre>@RestController<br>@RequestMapping(&quot;/posts&quot;)<br>public class PostController {<br><br>    @PostMapping(&quot;/create&quot;)<br>    public String addPost(@RequestBody Post post) {<br>        // Post creation logic<br>        return &quot;Post created with ID &quot; + post.getId();<br>    }<br>}</pre><p>Here, the <strong>Post service</strong> is independent. Similarly, there could be <strong>CommentService</strong>, <strong>UserService</strong>, and <strong>AnalyticsService</strong>, each running in its own container or server.</p><p><strong>Pros of Microservices:</strong></p><ul><li>Independent deployment and scaling of services.</li><li>Fault isolation: one service failure doesn’t crash the entire system.</li><li>Easier to integrate with modern cloud infrastructure.</li></ul><p><strong>Cons of Microservices:</strong></p><ul><li>More complex development and maintenance.</li><li>Requires communication between services.</li><li>Needs advanced DevOps skills.</li></ul><h3>When to Choose Monolith vs Microservices?</h3><ul><li><strong>Monolith:</strong> Best for <strong>small projects</strong>, prototypes, or when learning Java/Spring Boot. Quick to develop and easy to deploy.</li><li><strong>Microservices:</strong> Suitable for <strong>large-scale applications</strong> with multiple teams, frequent releases, and the need to scale independent modules.</li></ul><h3>My Learning Story</h3><p>When I refactored my Blog Management System into microservices, I split it into <strong>PostService</strong>, <strong>CommentService</strong>, <strong>UserService</strong>, and <strong>AnalyticsService</strong>, each running in a separate <strong>Spring Boot project with Docker containers</strong>. Initially, it was overwhelming handling <strong>service communication</strong>, <strong>databases</strong>, and <strong>logging</strong> was challenging. But over time, I realized I could deploy the <strong>AnalyticsService</strong> independently when adding new features without affecting other modules. Scaling <strong>PostService</strong> during peak traffic became trivial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=521384f41286" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Packaging 101 :  A Clear Path Through PyPI, pip & Virtual Envs]]></title>
            <link>https://sasuniwijerathne.medium.com/python-packaging-101-a-clear-path-through-pypi-pip-virtual-envs-038a531e77cb?source=rss-dee57e4a4b9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/038a531e77cb</guid>
            <dc:creator><![CDATA[Sasuniwijerathne]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 17:03:05 GMT</pubDate>
            <atom:updated>2025-11-20T17:03:05.886Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python Packaging 101 : A Clear Path Through PyPI, pip &amp; Virtual Envs</h3><p>When we build software in any programming language, managing <strong>dependencies</strong> (external libraries and tools our project needs) becomes extremely important. Every language ecosystem provides its own package manager and package registry to solve this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*jZHhC63woSNMbsQrcIiSIQ.jpeg" /></figure><p>Before we dive deep, let’s understand a key idea used in modern software development.</p><h3>What is a “Fat Artifact”?</h3><p>A <strong>fat artifact</strong> is an application bundle that includes:</p><ul><li>the <strong>app executable</strong></li><li>the <strong>language interpreter/runtime</strong></li><li>all <strong>required dependency libraries</strong> (API libraries)</li></ul><p>This ensures the application runs the same way on any machine , even if that machine doesn’t have the development tools installed.</p><p>Python doesn’t create fat artifacts by default, so we use tools like <strong>pip</strong> and <strong>virtual environments</strong> to manage dependencies cleanly.</p><p><strong>Dependency Management Across Languages</strong></p><ul><li><strong>Java</strong> → Maven / Gradle → Maven Central (search.maven.org)</li><li><strong>ECMAScript (JS/TS)</strong> → npm, yarn, webpack → npm Registry (npmjs.org)</li><li><strong>Python</strong> → pip → Python Package Index (pypi.org)</li></ul><p>Just like Java uses Maven and JavaScript uses npm/yarn, Python uses <strong>pip</strong> as its dependency manager.</p><h3>What is PyPI? (Python Package Index)</h3><p><strong>PyPI.org</strong> is the official online repository where all Python libraries are published.</p><p>It works just like:</p><ul><li>Maven Central for Java</li><li>npm registry for JavaScript</li></ul><p>Whenever we install a Python library using pip, it is fetched from <strong>PyPI</strong>.</p><h3>What is pip?</h3><p>pip (Python Installation Package) is the <strong>default dependency management tool</strong> for Python.<br> It is included automatically when you install Python from python.org.</p><h3>✔ Check your pip version:</h3><pre>pip -V</pre><h3>✔ Install a package:</h3><pre>pip install &lt;package-name&gt;</pre><h3>✔ Uninstall a package:</h3><pre>pip uninstall &lt;package-name&gt;</pre><h3>✔ List installed packages:</h3><pre>pip list</pre><h3>The Problem: pip Installs Packages Globally</h3><p>By default, pip installs every package <strong>system-wide</strong>, meaning:</p><ul><li>all projects share the same dependencies</li><li>version conflicts can appear easily</li></ul><p><em>This is </em><strong><em>not good</em></strong><em> for development.</em></p><p><em>That’s why Python gives us </em><strong><em>virtual environments</em></strong><em>.</em></p><h3>Virtual Environments — Project-wise Dependency Isolation</h3><p>A <strong>virtual environment</strong> is like a private Python workspace <strong>inside your project</strong>, containing:</p><ul><li>its own Python interpreter</li><li>its own pip</li><li>its own dependencies</li><li>isolated from other projects</li></ul><p>This prevents version conflicts and keeps your system clean.</p><p>Most developers create a folder called:</p><pre>.venv</pre><h4>Creating a Virtual Environment</h4><p>Run:</p><pre>python -m venv &lt;path-to-new-virtual-environment&gt;</pre><p>Example:</p><pre>python -m venv .venv</pre><p>This creates a .venv/ directory inside your project.</p><h3>Activating the Virtual Environment</h3><h4>On Windows (PowerShell):</h4><pre>.\.venv\Scripts\activate</pre><h4>On Linux / macOS:</h4><pre>source .venv/bin/activate</pre><p>Once activated, your terminal will show the environment name:</p><pre>(.venv)</pre><p>To check whether a virtual environment is active:</p><pre>echo $VIRTUAL_ENV</pre><h3>Deactivating the Virtual Environment</h3><pre>deactivate</pre><p>This returns your terminal to the global Python environment.</p><h3>Why Use Virtual Environments?</h3><p>✔ Project-wise dependency isolation<br> ✔ No version conflicts<br> ✔ Cleaner development workflow<br> ✔ Safer package management<br> ✔ Industry-standard best practice</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=038a531e77cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Redux — The Brain of State Management]]></title>
            <link>https://sasuniwijerathne.medium.com/react-redux-the-brain-of-state-management-47a1bb797a20?source=rss-dee57e4a4b9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/47a1bb797a20</guid>
            <dc:creator><![CDATA[Sasuniwijerathne]]></dc:creator>
            <pubDate>Wed, 05 Nov 2025 02:31:57 GMT</pubDate>
            <atom:updated>2025-11-05T02:31:57.248Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Redux — The Brain of State Management</h3><p>Imagine you’re running a busy restaurant. You have waiters (components) taking orders (user actions), a kitchen (store) where all recipes (state) live, and chefs (reducers) updating dishes based on those orders.</p><p>This is <strong>Redux</strong> — a <em>centralized system</em> that helps your entire React app share and manage data consistently, no matter how big the app grows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e16ZPhH9uvm6ZsaEL05dHw.jpeg" /></figure><h3>What Exactly is Redux?</h3><p>Redux is a <strong>state management library</strong> mostly used with React that helps you manage <em>global or application-level state</em> in a predictable way.</p><p>Instead of each component juggling its own useState values like spinning plates, Redux creates <strong>one central place</strong> (the store) to hold all the data your app cares about.</p><p>In short:<br> <strong>React = UI builder</strong><br> <strong>Redux = State manager</strong></p><h3>Why “Centralized State”?</h3><p>Think of a <em>giant office building</em> where each department (component) has its own tiny notebook for tracking tasks (local state). Communication gets messy. What if HR needs something from Finance? Or Marketing needs Sales data?</p><p>Redux fixes that by introducing <strong>a single big notebook</strong> (the <em>store</em>) where <em>everyone writes and reads the same truth</em>.</p><p>So when a user logs in, you can store that data (like name, email, token) in Redux and <em>every component</em> in your app can instantly access it without prop drilling or useContext.</p><h3>Core Building Blocks of Redux</h3><p>Let’s understand the core pieces each plays a unique role in the story.</p><h4>The Store — The Brain</h4><p>The <strong>store</strong> is like the <em>central command center</em> of your app. It holds the entire global state tree.</p><p>You only have <strong>one store</strong> per app.</p><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;<br>import userReducer from &#39;./userSlice&#39;<br><br>export const store = configureStore({<br>  reducer: {<br>    user: userReducer,<br>  },<br>})</pre><h4>Actions — The Messengers</h4><p>Actions are <strong>signals</strong> that tell Redux something happened like “User logged in” or “Product added to cart.”</p><p>They’re plain JavaScript objects with a type and (optionally) some data.</p><pre>{<br>  type: &#39;user/login&#39;,<br>  payload: { name: &#39;Sasuni&#39;, email: &#39;sasuni@gmail.com&#39; }<br>}</pre><h4>Reducers — The Chefs</h4><p>Reducers are <strong>functions</strong> that update the state based on actions.</p><p>They take the <em>current state</em> and an <em>action</em>, and return a <em>new state</em>.</p><pre>function userReducer(state = initialState, action) {<br>  switch (action.type) {<br>    case &#39;user/login&#39;:<br>      return { ...state, user: action.payload }<br>    default:<br>      return state<br>  }<br>}</pre><h4>Redux Slice — The Modern Combo Meal</h4><p>Redux Toolkit introduces <strong>slices</strong> a smarter way to group related state, actions, and reducers in one file.</p><p>Here’s an example slice for handling user login:</p><pre>import { createSlice } from &#39;@reduxjs/toolkit&#39;<br><br>const userSlice = createSlice({<br>  name: &#39;user&#39;,<br>  initialState: {<br>    user: null,<br>  },<br>  reducers: {<br>    login: (state, action) =&gt; {<br>      state.user = action.payload<br>    },<br>    logout: (state) =&gt; {<br>      state.user = null<br>    },<br>  },<br>})<br><br>export const { login, logout } = userSlice.actions<br>export default userSlice.reducer</pre><h4>Connecting Redux to React Components</h4><p>To make Redux data available inside your React app, wrap your app in a Provider from react-redux:</p><pre>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import { Provider } from &#39;react-redux&#39;<br>import { store } from &#39;./store&#39;<br>import App from &#39;./App&#39;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;<br>)</pre><h3>Using Redux Data in Components</h3><p>Use two hooks from React Redux:</p><ul><li>useSelector → read data from store</li><li>useDispatch → send actions to store</li></ul><pre>import { useSelector, useDispatch } from &#39;react-redux&#39;<br>import { login, logout } from &#39;./userSlice&#39;<br><br>function UserProfile() {<br>  const user = useSelector((state) =&gt; state.user.user)<br>  const dispatch = useDispatch()<br><br>  return (<br>    &lt;div&gt;<br>      {user ? (<br>        &lt;&gt;<br>          &lt;h2&gt;Welcome, {user.name}!&lt;/h2&gt;<br>          &lt;button onClick={() =&gt; dispatch(logout())}&gt;Logout&lt;/button&gt;<br>        &lt;/&gt;<br>      ) : (<br>        &lt;button<br>          onClick={() =&gt;<br>            dispatch(login({ name: &#39;Sasuni&#39;, email: &#39;sasuni@gmail.com&#39; }))<br>          }<br>        &gt;<br>          Login<br>        &lt;/button&gt;<br>      )}<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>Redux vs Context — The Subtle Difference</h3><p>You mentioned something perfect:</p><blockquote><em>“It’s like Context in Spring, but advanced.”</em></blockquote><p>Exactly.</p><p>Both <strong>Context API</strong> and <strong>Redux</strong> provide global state, but Redux gives more <strong>control, predictability, and structure</strong>.</p><p>You could say Redux and Context are two sides of the same coin both allow you to share data across your React app without passing props manually at every level. But the real difference lies in <strong>how much control and structure</strong> they offer. The <strong>Context API</strong> is simple and great for small applications or when you just need to share a theme, authentication status, or language settings. It works like a lightweight messenger that passes data through the component tree. <strong>Redux</strong>, on the other hand, steps in when your app grows bigger and your data flow becomes more complex. It’s like having a control tower every action, update, and state transition is tracked and predictable. Redux offers strict organization, debugging tools, middleware support, and time-travel debugging, which makes it ideal for large-scale apps. As you mentioned, it’s very much like <em>Context in Spring but advanced</em>, with added layers of structure and power that make managing application-level state more reliable and scalable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a1bb797a20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Power of Re-renders: How React Keeps the UI Alive]]></title>
            <link>https://sasuniwijerathne.medium.com/the-hidden-power-of-re-renders-how-react-keeps-the-ui-alive-d6c4833f297b?source=rss-dee57e4a4b9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6c4833f297b</guid>
            <dc:creator><![CDATA[Sasuniwijerathne]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 05:41:58 GMT</pubDate>
            <atom:updated>2025-11-03T05:41:58.827Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re building your dream app ,maybe a cute “Pet Tracker” that helps users keep track of their pets’ feeding and walking schedules. You start small- a few pages, some data, and an idea. That’s when you meet the real heroes of React <strong>Components</strong>.</p><h3>Two Ways to Build Components</h3><p>In React, everything is a component tiny pieces that combine to build the UI.</p><h3>1. Functional Components (Modern Way)</h3><p>Functional components are simple JavaScript functions that return JSX.<br> They’re the heart of modern React development clean, easy to test, and hook-friendly.</p><pre>function PetCard({ name, age }) {<br>  return (<br>    &lt;div className=&quot;card&quot;&gt;<br>      &lt;h2&gt;{name}&lt;/h2&gt;<br>      &lt;p&gt;Age: {age}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>2. Class Components</h3><p>Before Hooks were born, React used <strong>class components</strong>. They were powerful but verbose managing state and lifecycle required extra code.</p><pre>class PetCard extends React.Component {<br>  render() {<br>    return (<br>      &lt;div className=&quot;card&quot;&gt;<br>        &lt;h2&gt;{this.props.name}&lt;/h2&gt;<br>        &lt;p&gt;Age: {this.props.age}&lt;/p&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><h3>Props — Passing Data Between Components</h3><p>Props are how data flows <strong>from parent to child components</strong>.</p><pre>function PetList() {<br>  return (<br>    &lt;div&gt;<br>      &lt;PetCard name=&quot;Bella&quot; age={2} /&gt;<br>      &lt;PetCard name=&quot;Charlie&quot; age={5} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>If you want to extract data from props neatly, use <strong>object destructuring</strong>:</p><pre>function PetCard({ name, age }) {<br>  return &lt;p&gt;{name} is {age} years old.&lt;/p&gt;;<br>}</pre><h3>Event Handling — Making Your UI Come Alive</h3><p>React lets you handle events like clicks or form submissions easily.</p><pre>function PetButton() {<br>  function handleClick() {<br>    alert(&quot;Woof! You clicked me!&quot;);<br>  }<br><br>  return &lt;button onClick={handleClick}&gt;Click Me&lt;/button&gt;;<br>}</pre><p>You’re not calling handleClick() directly you’re passing it as a reference, so it only runs when clicked.</p><h3>State — The Data That Changes</h3><p>State represents <strong>the dynamic data</strong> in a component what React uses to re-render the UI when something changes.</p><pre>import { useState } from &quot;react&quot;;<br><br>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;You clicked {count} times!&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Click me!&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Every time you click the button, the <strong>state updates</strong> and React automatically <strong>re-renders</strong> the component.</p><p>That’s the magic of React your UI stays in sync with your data.</p><h3>The Component Lifecycle — The Story of a Component’s Life</h3><p>Think of your component as a little creature that lives in the browser.<br> It has <strong>three life stages</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*G_y7HF7dPTMOanDR7z5wHw.jpeg" /></figure><ol><li><strong>Mounting</strong> — It’s born and added to the screen.<br> → useEffect(() =&gt; { console.log(&quot;Mounted!&quot;) }, [])</li><li><strong>Updating</strong> — It changes (maybe the user clicked something).<br> → useEffect(() =&gt; { console.log(&quot;Updated!&quot;) })</li><li><strong>Unmounting</strong> — It leaves the screen.<br> → useEffect(() =&gt; { return () =&gt; console.log(&quot;Unmounted!&quot;) }, [])</li></ol><pre>import { useEffect, useState } from &quot;react&quot;;<br><br>function PetStatus() {<br>  const [name, setName] = useState(&quot;Buddy&quot;);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;Component mounted&quot;);<br><br>    return () =&gt; {<br>      console.log(&quot;Component unmounted&quot;);<br>    };<br>  }, []);<br><br>  return &lt;h3&gt;{name} is happy today!&lt;/h3&gt;;<br>}</pre><p>This lifecycle understanding helps you manage resources, animations, and data fetching efficiently.</p><h3>Prop Drilling — When Passing Props Gets Messy</h3><p>Imagine you have a User component that needs to share data with a deeply nested PetDetails component. You end up passing props through many layers that’s <strong>prop drilling</strong>.</p><pre>function App() {<br>  const user = { name: &quot;Sasuni&quot; };<br>  return &lt;Dashboard user={user} /&gt;;<br>}<br><br>function Dashboard({ user }) {<br>  return &lt;Profile user={user} /&gt;;<br>}<br><br>function Profile({ user }) {<br>  return &lt;PetDetails user={user} /&gt;;<br>}<br><br>function PetDetails({ user }) {<br>  return &lt;p&gt;Owner: {user.name}&lt;/p&gt;;<br>}</pre><h3>useContext — The Antidote to Prop Drilling</h3><p>Instead of passing data manually, you can use <strong>Context</strong> to share data <strong>directly</strong> with deeply nested components.</p><pre>import { createContext, useContext } from &quot;react&quot;;<br><br>const UserContext = createContext();<br><br>function App() {<br>  const user = { name: &quot;Sasuni&quot; };<br><br>  return (<br>    &lt;UserContext.Provider value={user}&gt;<br>      &lt;Dashboard /&gt;<br>    &lt;/UserContext.Provider&gt;<br>  );<br>}<br><br>function Dashboard() {<br>  return &lt;Profile /&gt;;<br>}<br><br>function Profile() {<br>  const user = useContext(UserContext);<br>  return &lt;p&gt;Owner: {user.name}&lt;/p&gt;;<br>}</pre><h3>Why Hooks Matter</h3><p>Hooks gave functional components <strong>the power that class components once held</strong>, plus simplicity and flexibility.</p><p>They:</p><ul><li>Make state logic reusable</li><li>Simplify lifecycle management</li><li>Improve readability and performance</li><li>Reduce boilerplate code</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6c4833f297b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Story of React’s Virtual DOM vs Actual DOM]]></title>
            <link>https://sasuniwijerathne.medium.com/the-story-of-reacts-virtual-dom-vs-actual-dom-998d128a7042?source=rss-dee57e4a4b9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/998d128a7042</guid>
            <dc:creator><![CDATA[Sasuniwijerathne]]></dc:creator>
            <pubDate>Sun, 28 Sep 2025 18:28:21 GMT</pubDate>
            <atom:updated>2025-09-28T18:28:21.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0hK1AXXA_uktiJfVOixg7g.png" /></figure><p>Imagine this:</p><p>You’re a painter, and you’ve just finished a huge <strong><em>mural on the wall</em></strong>. It’s beautiful, detailed, and colorful. But then, your friend comes in and says:</p><blockquote><em>“Hey, can you change the color of just that one flower?”</em></blockquote><p>Now, if you’re working directly on the wall (the <strong>Actual DOM</strong>), you’ll need to carefully set up your paints, climb the ladder, and maybe even repaint a large portion of the mural. It’s <strong>time-consuming</strong> and <strong>tiring</strong>.</p><p>But what if you had a <strong>sketchbook version</strong> of the mural (the <strong>Virtual DOM</strong>)?</p><ul><li>You could quickly sketch the change on paper.</li><li>Compare the new sketch with the old one.</li><li>And then only repaint <strong>that one flower</strong> on the wall.</li></ul><h4><strong>Faster. Cleaner. Smarter.</strong></h4><p>That’s exactly how <strong>React works with the DOM</strong>.</p><h3>How the Story Plays Out in React</h3><ol><li><strong>The First Painting (Initial Render)</strong></li></ol><ul><li>React takes your components and builds a <strong>Virtual DOM tree</strong> (the sketchbook).</li><li>Then, it paints the <strong>Actual DOM</strong> (the wall).</li></ul><p><strong>2. The Update Request (State/Props Change)</strong></p><ul><li>Something changes: a button is clicked, a counter increases, a new comment appears.</li><li>React redraws the sketch in the Virtual DOM with these changes.</li></ul><p><strong>3. The Comparison (Diffing Algorithm)</strong></p><ul><li>React looks at the old sketch and the new sketch.</li><li>“Oh! Only the flower changed.”</li><li>It ignores everything else.</li></ul><p><strong>4. The Touch-Up (Reconciliation)</strong></p><ul><li>Instead of repainting the whole mural, React goes straight to the flower and updates only that spot.</li><li>The wall (Actual DOM) looks updated, but the effort was minimal.</li></ul><h3>Code Example in Our Story</h3><pre>import React, { useState } from &quot;react&quot;;<br><br>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Counter: {count}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increase&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><p>Moral of the Story</p><ul><li><strong>Actual DOM</strong> = the real mural ➡️slow to repaint.</li><li><strong>Virtual DOM</strong> = the sketchbook ➡️ quick to redraw, compare, and plan.</li><li>React uses the sketchbook first, then carefully updates only what’s necessary on the real mural.</li></ul><p>This is why React apps feel <strong>fast, efficient, and smooth</strong>, even when they grow big.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=998d128a7042" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing in Spring Boot: A Complete Guide to Application & Software Testing]]></title>
            <link>https://sasuniwijerathne.medium.com/testing-in-spring-boot-a-complete-guide-to-application-software-testing-9a4d92c59292?source=rss-dee57e4a4b9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a4d92c59292</guid>
            <dc:creator><![CDATA[Sasuniwijerathne]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 18:39:13 GMT</pubDate>
            <atom:updated>2025-08-14T18:39:13.171Z</atom:updated>
            <content:encoded><![CDATA[<p>Software testing is not just a phase in development .it’s a <strong>continuous process</strong> that ensures the application works as intended, is reliable, and meets user expectations. Whether you’re developing a <strong>web application</strong> or a <strong>mobile app</strong>, testing plays a critical role in validating features, performance, and stability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ec6U7jF-_4xcXD9GEuYc8w.png" /></figure><h3>Why We Need Testing</h3><p>Testing helps us:</p><ul><li><strong>Validate functionality</strong> — Ensure the system behaves as expected.</li><li><strong>Catch defects early</strong> — Fixing issues early is far cheaper than post-release fixes.</li><li><strong>Maintain quality</strong> — Keep the app stable during continuous development.</li><li><strong>Check performance</strong> — Measure loading times and request handling.</li><li><strong>Verify data management</strong> — Ensure data is stored, updated, and retrieved correctly.</li><li><strong>Fulfill critical requirements</strong> — Meet business, technical, and compliance standards.</li></ul><p>In real-world projects, testing often involves both <strong>manual</strong> and <strong>automated</strong> approaches.</p><h3>🖐 Manual Testing vs 🤖 Automated Testing</h3><h4>Manual Testing</h4><p>Some test cases are <strong>hard to automate, </strong>especially when:</p><ul><li>Human observation is needed.</li><li>Exploratory testing is done to discover unexpected behavior.</li><li>Complex hardware interaction is involved.</li></ul><p>Example: Checking if a mobile app UI feels smooth when scrolling on different devices.</p><h4>Automated Testing</h4><p>For repetitive, predictable, or high-volume checks, automation saves time and ensures consistency.<br> Common tools:</p><ul><li><strong>JUnit &amp; Mockito</strong> (Unit testing in Spring Boot)</li><li><strong>Selenium</strong> (UI testing)</li><li><strong>Postman </strong>(API testing)</li><li><strong>JMeter </strong>(Performance/load testing)</li></ul><p>Example: Automatically verifying that a REST API returns the correct JSON structure.</p><h3>Software Testing Methods in SWE</h3><p>In <strong>Software Engineering (SWE)</strong>, testing is structured into multiple layers:</p><h4>1️⃣ Unit Testing</h4><ul><li><strong>Definition</strong>: Testing small, isolated parts (units) of code, usually individual methods or classes.</li><li><strong>Purpose</strong>: Ensure each part works <strong>independently</strong>.</li><li><strong>Example in Spring Boot</strong>:<br> Testing a service method that calculates discounts without connecting to the database.</li><li><strong>Tools</strong>: JUnit, Mockito.</li></ul><pre>@Test<br>    void shouldSaveProduct(){<br>        // arrange data --- data preparation<br>        when(productRepository.save(any(Product.class))).thenReturn(product);<br><br>        // action --- write test logic<br>        Product savedProduct = productService.saveProduct(product);<br><br>        // assert --- verify the result<br>        Assertions.assertNotNull(savedProduct);<br>        Assertions.assertEquals(product, savedProduct);<br>        Assertions.assertEquals(product.getId(), savedProduct.getId());<br>        verify(productRepository,times(1)).save(any(Product.class));<br>    }</pre><h4>2️⃣ Integration Testing</h4><ul><li><strong>Definition</strong>: Testing how multiple layers or components <strong>work together</strong>.</li><li><strong>Purpose</strong>: Verify proper communication between layers.</li><li><strong>Example in Spring Boot</strong>:<br> Checking if your REST API correctly fetches data from the database.</li><li><strong>Tools</strong>: Spring Boot Test, Testcontainers.</li></ul><h4>3️⃣ End-to-End (E2E) Testing</h4><ul><li><strong>Definition</strong>: Simulating <strong>real user scenarios</strong> from start to finish.</li><li><strong>Purpose</strong>: Ensure the entire application flow works as expected.</li><li><strong>Example</strong>:<br> A user signs up → verifies email → logs in → adds an item to the cart → checks out.</li></ul><p>💡 <strong>What is a User Story?</strong><br> A user story describes a feature from an <strong>end-user’s perspective</strong>.</p><p><strong>Example:</strong></p><blockquote><em>“As a registered customer, I want to add products to my shopping cart so that I can purchase them later.”</em></blockquote><p>E2E testing ensures <strong>this story flow works without breaking</strong>.</p><h3>⚫ Black Box Testing vs ⚪ White Box Testing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5u1Npn8gkZ16HnAy1Yq51g.png" /></figure><p><strong>Example in Spring Boot:</strong></p><ul><li><strong>Black Box</strong>: Send an API request /login and check the response.</li><li><strong>White Box</strong>: Test the authentication method to ensure it uses BCrypt password encoding.</li></ul><h3>User Acceptance Testing (UAT)</h3><ul><li><strong>Definition</strong>: Performed by <strong>end-users or stakeholders</strong> to validate the system meets their requirements before release.</li><li><strong>Purpose</strong>: Ensure business needs are fulfilled.</li><li><strong>Example</strong>:<br> A client uses the application in a staging environment to confirm that all booking features work for their pet care business.</li></ul><h3>Linking Web &amp; Mobile App Testing</h3><p>When your Spring Boot backend powers <strong>both web and mobile apps</strong>, you must:</p><ul><li>Test <strong>loading times</strong> for different devices.</li><li>Validate <strong>API requests</strong> and responses.</li><li>Check <strong>data consistency</strong> across platforms.</li><li>Perform <strong>load testing</strong> for high traffic scenarios.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a4d92c59292" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Web Security Matters in Spring Boot and How JWT Protects Your APIs]]></title>
            <link>https://sasuniwijerathne.medium.com/why-web-security-matters-in-spring-boot-and-how-jwt-protects-your-apis-4c2bdc9f2e4a?source=rss-dee57e4a4b9b------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c2bdc9f2e4a</guid>
            <dc:creator><![CDATA[Sasuniwijerathne]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 19:04:15 GMT</pubDate>
            <atom:updated>2025-08-12T19:04:15.214Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s connected world, security isn’t just a feature , it’s a <strong>necessity</strong>. Whether you’re building an e-commerce app, a healthcare platform, or a banking system, securing your application means protecting your users, your business, and your reputation.</p><h3>Why We Need Web Security</h3><h4>1. Data Protection</h4><p>Every modern app processes sensitive data — personal details, financial transactions, health records. Compromising this data can lead to devastating consequences.</p><h4>2. Compliance with Standards</h4><p>Different industries have specific legal and regulatory standards:</p><ul><li><strong>HIPAA</strong> — Protects health information in the US healthcare industry.</li><li><strong>GDPR</strong> — Governs personal data protection in the EU.</li><li><strong>PCI-DSS</strong> — Ensures secure handling of payment card data.</li></ul><h4>3. Building User Trust</h4><p>Security is key to customer confidence. Users will not interact with — let alone share sensitive data with — an insecure platform.</p><h4>4. Regional Access Control</h4><p>Web security allows limiting access based on <strong>IP location</strong> or <strong>geographical regions</strong>, ensuring only authorized countries or regions can reach your service.</p><h3>Common Web Vulnerabilities</h3><ol><li><strong>SQL Injection </strong>— Injecting malicious SQL queries to manipulate the database.</li><li><strong>Cross-Site Scripting</strong> — Injecting malicious JavaScript into web pages.</li><li><strong>Cross-Site Request Forgery (CSRF)</strong> — Forcing users to perform actions without their consent.</li><li><strong>Insecure Direct Object References </strong>— Accessing unauthorized resources by manipulating identifiers.</li><li><strong>Broken Authentication</strong> — Poorly implemented login systems that attackers can bypass.</li><li><strong>Sensitive Data Exposure</strong> — Transmitting sensitive information without encryption.</li><li><strong>Security Misconfiguration</strong> — Leaving default credentials, unnecessary ports, or unused services enabled.</li><li><strong>Broken Access Control</strong> — Allowing users to access features or data beyond their permissions.</li><li><strong>Denial of Service (DoS)</strong> — Flooding the server with traffic to make the application unavailable.</li></ol><h3>Web Security Fundamentals</h3><ol><li><strong>Authentication</strong> — Verifying the user’s identity.</li><li><strong>Authorization</strong> — Determining what authenticated users are allowed to do.</li><li><strong>Cryptography</strong> — The science of secure communication.</li><li><strong>Encryption</strong> — Locking data with a <strong>digital key</strong> so only the intended recipient can read it.</li><li><strong>Data Hashing</strong> — Creating a <strong>digital fingerprint</strong> that cannot be reversed.</li><li><strong>Tokens</strong> — Digital visitor passes to authenticate API requests.</li><li><strong>Session Management</strong> — Controlling how long a user stays logged in and monitoring active sessions.</li></ol><h3>Security Techniques to Implement</h3><ul><li><strong>HTTPS (SSL)</strong> — Secure your domain with encryption in transit.</li><li><strong>Content Security Policy (CSP)</strong> — Prevent XSS by restricting what scripts can run.</li><li><strong>Input Validation &amp; Output Encoding</strong> — Prevent malicious input from being executed.</li><li><strong>Base64 Encoding</strong> — Safe data transmission.</li></ul><p><em>ex : QR code generation (not for actual security).</em></p><ul><li><strong>Least Privilege Principle</strong> — Give users only the permissions they need.</li><li><strong>Rate Limiting &amp; IP Blocking</strong> — Prevent brute force attacks by limiting requests per second.</li><li><strong>MFA (Multi-Factor Authentication)</strong> &amp; <strong>2FA (Two-Factor Authentication)</strong> — Require additional verification beyond passwords.</li></ul><h3>Spring Boot + Spring Security</h3><p>Spring Boot makes it easy to secure your applications with <strong>Spring Security</strong>, a powerful framework providing authentication, authorization, and protection against common attacks.</p><p><strong>Key Components:</strong></p><ul><li><strong>Security Filter Chain</strong> — Processes every request for security checks.</li><li><strong>Authentication Manager</strong> — Handles login verification.</li><li><strong>UserDetailsService</strong> — Loads user-specific data.</li><li><strong>Security Context Holder</strong> — Stores authentication details.</li><li><strong>Password Encoder</strong> — Hashes passwords securely.</li></ul><h3>JWT (JSON Web Token)</h3><p>JWT is a <strong>compact, stateless</strong> way to securely transmit information between parties.<br> <strong>Structure:</strong></p><pre>Header + Payload + Signature</pre><ul><li><strong>Header</strong> — Specifies token type and hashing algorithm.</li><li><strong>Payload</strong> — Contains user data and claims.</li><li><strong>Signature</strong> — Ensures the token hasn’t been tampered with, generated using a secret key.</li></ul><p><strong>How It Works in Spring Boot:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*x-gMtb2WYZO6LKTuw5sB-w.png" /></figure><ul><li>The server issues a JWT after successful authentication.</li><li>Clients send this token in the Authorization header when accessing protected APIs.</li><li>The server validates the token before processing the request.</li></ul><p><strong>Example:</strong><br> If you send a valid JWT in the request header, you can access protected APIs from <strong>anywhere</strong>, as long as the token is still valid.</p><p><strong>Token Expiry:</strong></p><ul><li>Short-lived tokens require frequent re-authentication.</li><li>Long-lived tokens, like those used by Facebook, allow continuous login using <strong>refresh tokens</strong> in the background.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c2bdc9f2e4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>