<?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 Awa precious on Medium]]></title>
        <description><![CDATA[Stories by Awa precious on Medium]]></description>
        <link>https://medium.com/@awaprecious3t?source=rss-9e0881aa60c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*AGtSvXE6thJBOJ8r</url>
            <title>Stories by Awa precious on Medium</title>
            <link>https://medium.com/@awaprecious3t?source=rss-9e0881aa60c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 02:57:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@awaprecious3t/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[Why Did the App Log Me Out? Sessions and Tokens Explained]]></title>
            <link>https://medium.com/@awaprecious3t/why-did-the-app-log-me-out-sessions-and-tokens-explained-036be1ca4479?source=rss-9e0881aa60c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/036be1ca4479</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Awa precious]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 14:05:44 GMT</pubDate>
            <atom:updated>2026-11-16T14:05:44.707Z</atom:updated>
            <content:encoded><![CDATA[<p>Nov 16, 2026 · @PCodes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSd5QU8E1IaRaEIxceraDQ.png" /></figure><p>You open your banking app, check your balance, and put the phone down to answer the door. Five minutes later you pick it up again. “Your session has expired. Please log in again.”</p><p>Then you open WhatsApp and it still knows who you are since the first day.</p><p>Neither app is broken but both made a deliberate choice about how long to trust you after you prove who you are. The banking app chose minutes but WhatsApp chose months. This article explains how apps remember you, why that memory has to expire, and how to build it properly in Spring Boot.</p><h3>How apps remember you</h3><p>Every request your phone sends to a server arrives as a stranger. HTTP has no memory so without help, the server would ask for your password on every tap.</p><p>So after you log in once, the app needs some proof it can show on every request. There are two common ways to do this.</p><h3>Sessions: the server keeps the list</h3><p>Think of a nightclub that gives you a ticket at the door and writes your name in a book. When you come back from the toilet, the bouncer checks the ticket against the book.</p><p>With sessions, the server creates a record when you log in, “session 8f3a belongs to John”, and gives your browser only the session ID, usually in a cookie. On each request, the server looks the ID up in its list.</p><p>The strength: the server is in control. To log someone out, it deletes their line from the book, and the ticket stops working instantly.</p><p>The cost: every request needs a lookup, and with several servers they all have to share the book, usually in Redis or the database.</p><h3>Tokens: you carry the proof</h3><p>Now think of a visitor badge at an office. Reception checks your ID once and prints a badge with your name, your access level and an expiry time, sealed with the company’s stamp. Every door scans the badge and checks the stamp. Nobody calls reception again.</p><p>A JWT (JSON Web Token) is that badge. It contains your user ID, your role and an expiry time, signed with a secret only the server knows. Any server can check the signature and trust what’s inside, with no lookup at all.</p><p>The strength: fast, and easy to use across many servers and mobile apps.</p><p>The cost is the flip side of the strength. Because no one checks with reception, there’s no easy way to cancel a badge before it expires. If a token is stolen, it works for the thief until its expiry time.</p><p>That single fact explains almost everything else in this article.</p><h3>Why tokens expire</h3><p>A token that never expires is a key that works forever. Phones get stolen, laptops get shared, and tokens leak into logs and browser extensions. Whoever holds the token is you, for as long as it lasts.</p><p>So the expiry time is a trade-off:</p><ul><li><strong>Short expiry</strong> limits the damage of a stolen token, but forces users to log in again and again.</li><li><strong>Long expiry</strong> is comfortable, but a stolen token stays useful for a long time.</li></ul><p>The bank and WhatsApp didn’t pick different points on that trade-off by accident. A stolen banking session can empty an account. A stolen WhatsApp session is serious, but WhatsApp has other protections, and nobody would use a messaging app that logged them out every five minutes.</p><h3>Access tokens and refresh tokens</h3><p>Most modern apps avoid the trade-off by using two tokens.</p><ul><li><strong>The access token</strong> is the visitor badge. It’s short-lived, often 15 minutes, and sent with every request.</li><li><strong>The refresh token</strong> is a longer pass that lives for days or months. It has one job: getting a new access token when the old one expires.</li></ul><p>Here’s how a normal day looks:</p><ol><li>You log in. The server gives you both tokens.</li><li>For 15 minutes, every request carries the access token.</li><li>The access token expires. The server answers 401 Unauthorized.</li><li>The app quietly sends the refresh token to /auth/refresh and gets a fresh access token.</li><li>The app retries the request. You never notice.</li></ol><p>This is how WhatsApp-style apps keep you signed in for months while staying safe. The token that travels on every request expires quickly, so a stolen one is soon useless. The long-lived refresh token is used rarely and, unlike the access token, the server keeps a record of it. That record is what makes logging out possible.</p><h3>Logging out for real</h3><p>Here’s a common mistake. The user taps “Log out”, the app deletes the JWT from the phone, and everyone assumes the user is logged out.</p><p>The phone forgot the token. The server didn’t, because it never knew about it. If someone copied that token earlier, it still works until it expires.</p><p>The fix is to keep the server in charge of the part that lasts:</p><ul><li>Store refresh tokens in the database, hashed like passwords.</li><li>On logout, mark the refresh token as revoked. The app can’t get new access tokens with it any more.</li><li>The current access token still works until it expires, but that’s at most 15 minutes.</li></ul><p>The same table gives you two more features almost for free:</p><ul><li><strong>“Log out of all devices”</strong>: revoke every refresh token for that user. Useful after a password change or a stolen phone.</li><li><strong>Rotation</strong>: each time a refresh token is used, issue a new one and revoke the old. If an old token ever shows up again, someone copied it, so revoke all of that user’s tokens and make them log in.</li></ul><p>If 15 minutes is still too long for your app, as it might be for a bank, you can also keep a short blocklist of revoked access token IDs in Redis, with each entry expiring when the token would.</p><h3>Building it in Spring Boot</h3><h3>The refresh token table</h3><pre>CREATE TABLE refresh_tokens (<br>    id          UUID PRIMARY KEY,<br>    user_id     BIGINT       NOT NULL,<br>    token_hash  CHAR(64)     NOT NULL UNIQUE,<br>    expires_at  TIMESTAMPTZ  NOT NULL,<br>    revoked_at  TIMESTAMPTZ<br>);</pre><p>We store a SHA-256 hash, never the token itself. If the database leaks, the attacker gets hashes they can’t use.</p><h3>Issuing both tokens</h3><p>The access token is a JWT, signed with Spring Security’s JwtEncoder. The refresh token doesn&#39;t need to be a JWT at all: a long random string is simpler and just as safe, because the server always looks it up.</p><pre>@Service<br>public class TokenService {<br><br>    private static final Duration ACCESS_TTL = Duration.ofMinutes(15);<br>    private static final Duration REFRESH_TTL = Duration.ofDays(30);<br>    private final JwtEncoder jwtEncoder;<br>    private final RefreshTokenRepository refreshTokens;<br>    private final SecureRandom random = new SecureRandom();<br>    public TokenService(JwtEncoder jwtEncoder, RefreshTokenRepository refreshTokens) {<br>        this.jwtEncoder = jwtEncoder;<br>        this.refreshTokens = refreshTokens;<br>    }<br>    public TokenPair issue(User user) {<br>        Instant now = Instant.now();<br>        JwtClaimsSet claims = JwtClaimsSet.builder()<br>            .subject(user.getId().toString())<br>            .claim(&quot;role&quot;, user.getRole().name())<br>            .issuedAt(now)<br>            .expiresAt(now.plus(ACCESS_TTL))<br>            .build();<br>        String accessToken = jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();<br>        byte[] bytes = new byte[32];<br>        random.nextBytes(bytes);<br>        String refreshToken = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);<br>        refreshTokens.save(new RefreshToken(<br>            UUID.randomUUID(), user.getId(), sha256(refreshToken), now.plus(REFRESH_TTL)));<br>        return new TokenPair(accessToken, refreshToken);<br>    }<br>}</pre><h3>Refreshing, with rotation</h3><pre>@Transactional<br>public TokenPair refresh(String presentedToken) {<br>    RefreshToken stored = refreshTokens.findByTokenHash(sha256(presentedToken))<br>        .orElseThrow(InvalidRefreshTokenException::new);<br>    if (stored.isRevoked()) {<br>        // This token was already used or logged out. Someone may have copied it.<br>        refreshTokens.revokeAllForUser(stored.getUserId(), Instant.now());<br>        throw new InvalidRefreshTokenException();<br>    }<br>    if (stored.isExpired()) {<br>        throw new InvalidRefreshTokenException();<br>    }<br>    stored.revoke(Instant.now());<br>    User user = userRepository.findById(stored.getUserId()).orElseThrow();<br>    return issue(user);<br>}</pre><p>Every refresh retires the old token and hands out a new pair. A replayed token triggers a full logout for that user, which protects them even if the thief refreshes first.</p><p>One detail: two refresh requests for the same token can arrive together, for example from two browser tabs. That’s a check-then-act, the race condition pattern again. Load the token with a PESSIMISTIC_WRITE lock so only one request can use it.</p><h3>Logging out</h3><pre>@PostMapping(&quot;/auth/logout&quot;)<br>public ResponseEntity&lt;Void&gt; logout(@RequestBody LogoutRequest request) {<br>    refreshTokens.findByTokenHash(sha256(request.refreshToken()))<br>        .ifPresent(token -&gt; token.revoke(Instant.now()));<br>    return ResponseEntity.noContent().build();<br>}<br><br>@PostMapping(&quot;/auth/logout-all&quot;)<br>public ResponseEntity&lt;Void&gt; logoutAll(@AuthenticationPrincipal Jwt jwt) {<br>    refreshTokens.revokeAllForUser(Long.valueOf(jwt.getSubject()), Instant.now());<br>    return ResponseEntity.noContent().build();<br>}</pre><p>Logout always returns 204, even for an unknown token. There&#39;s nothing useful to tell an attacker.</p><h3>Checking the access token</h3><p>Spring Security’s resource server checks the signature and expiry on every request for you:</p><pre>http.oauth2ResourceServer(oauth -&gt; oauth.jwt(Customizer.withDefaults()));</pre><p>Expired or tampered tokens get 401 before your controller runs.</p><h3>Where the app keeps the tokens</h3><ul><li><strong>Mobile apps:</strong> use the platform’s secure storage, Keychain on iOS and Keystore on Android. React Native libraries such as react-native-keychain wrap both.</li><li><strong>Web apps:</strong> put the refresh token in an HttpOnly, Secure, SameSite cookie, so page scripts can&#39;t read it. Keep the access token in memory, not in localStorage, where any injected script can steal it.</li></ul><h3>Choosing the lifetimes</h3><p>There’s no single right number. Ask what a thief could do with the account.</p><ul><li><strong>Money moves here</strong> (banking, wallets, trading): short access tokens, short or no refresh tokens, a logout after a few minutes of inactivity, and a fresh PIN or fingerprint before sensitive actions like transfers.</li><li><strong>Personal but not financial</strong> (messaging, social, e-commerce): 15-minute access tokens with refresh tokens that last weeks or months, rotated on every use.</li><li><strong>Low risk</strong> (a news app, a recipe app): long refresh tokens are fine.</li></ul><p>Many apps mix these. You stay logged in to browse, and the app asks for your PIN again before you pay. That’s the best of both: comfort for reading, a fresh check for anything costly.</p><h3>The takeaway</h3><p>When the bank logs you out after five minutes, it’s not being lazy or broken. It’s limiting how long a stolen phone stays useful. When WhatsApp keeps you in for months, it’s using refresh tokens to stay comfortable without staying careless.</p><p>If you build login, remember three things:</p><ol><li>Deleting a token on the phone isn’t logging out. Revoke it on the server.</li><li>Keep the token that travels on every request short-lived.</li><li>Pick the lifetime by asking what a thief could do with the account.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=036be1ca4479" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hexagonal Architecture: Plug Your Application Into Anything]]></title>
            <link>https://medium.com/@awaprecious3t/hexagonal-architecture-plug-your-application-into-anything-d9a9c4e941d2?source=rss-9e0881aa60c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9a9c4e941d2</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Awa precious]]></dc:creator>
            <pubDate>Fri, 06 Nov 2026 13:45:49 GMT</pubDate>
            <atom:updated>2026-11-06T13:45:49.452Z</atom:updated>
            <content:encoded><![CDATA[<p>Nov 6, 2026 · @PCodes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2cgKWIrYLFwMLEIZreENLg.png" /><figcaption>The Backend Engineering Series: Hexagonal Architecture</figcaption></figure><p>An online shop takes payments with MTN MoMo. The code works, and it lives where most MVPs put it: inside the controller. The controller reads the request, loads the order from the database, checks if it hasn’t been paid, builds the MoMo request, calls MoMo, reads the response, and marks the order as paid. Maybe about sixty lines, all in one method.</p><p>Then the business asks for Orange Money.</p><p>The developer copies the method and edits it for Orange. Now the rule “an order can’t be paid twice” exists in two places. A month later, someone fixes a bug in the MoMo version and forgets the Orange one. Then the shop wants to test the payment rules, and finds out it can’t, because every test needs a real database and a real MoMo account.</p><p>Nothing here is a bad line of code. The problem is where things live. The business rules are glued to the tools they happen to use today.</p><p>Hexagonal architecture is a way to unglue them.</p><h3>The idea</h3><p>Think of Hexagonal Architecture like traveling from Cameroon to London with your laptop. In Cameroon, we use a 2-pin plug, but London uses a 3-pin socket. You don’t buy a new laptop; you just use a travel adapter. Your laptop works exactly the same because the adapter handles the difference.</p><p>Hexagonal architecture brings this exact setup to your code:</p><ul><li><strong>The Laptop (Your Core Logic):</strong> This is your main business logic sitting safely in the middle. It handles the core rules (like “accept a MoMo payment” or “save an order”) without caring about the technical wiring.</li><li><strong>The Travel Adapter (Your Code Adapters):</strong> These are small outer pieces of code. They translate your core logic’s needs into real-world tools like PostgreSQL, MTN MoMo, or Orange Money.</li></ul><p>If a tool changes, like swapping a database or updating a payment API, you don’t rebuild your app. <strong>You just write a new adapter, plug it in, and your core code keeps running perfectly.</strong></p><p>Alistair Cockburn described the pattern in the mid-2000s and called it “ports and adapters”. The hexagon is just a drawing choice. It has six sides to suggest the app can have many connections, not a fixed number. Nothing in the code is shaped like a hexagon.</p><h3>The three parts</h3><h3>The core</h3><p>The core holds your business rules like: “an order can’t be paid twice”, “a refund can’t be bigger than the payment”, “a driver can’t accept two rides at once”. It’s plain Java. No Spring annotations, no JPA, no HTTP. If you deleted every framework from your project, the core would still compile.</p><h3>Ports</h3><p>Ports are interfaces that the core defines. A port says what the core needs, in the core’s own words:</p><ul><li>“I need to find and save orders.”</li><li>“I need to charge a customer.”</li></ul><p>There are two directions. Inbound ports are how the outside world asks the core to do something, like “pay this order”. Outbound ports are how the core asks the outside world for something, like “charge this phone number”.</p><h3>Adapters</h3><p>Adapters are the code that plugs real technology into the ports. A REST controller is an inbound adapter: it turns an HTTP request into a call to the core. A JPA repository and a MoMo client are outbound adapters: they turn the core’s needs into SQL queries and API calls.</p><p>Here’s the whole picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VsFf1rb8IBA0hT9H_9btnQ.png" /><figcaption>Image illustrating the hexagonal architecture</figcaption></figure><p>The one rule that makes it work: dependencies point inward. Adapters know about the core. The core never knows about adapters. The core has never heard of MoMo.</p><h3>Building it in Spring Boot</h3><p>Let’s rebuild the shop’s payment feature.</p><h3>The folders</h3><pre>com.codewithpcodes.shop.order<br>├── domain<br>│   ├── Order.java<br>│   └── OrderStatus.java<br>├── application<br>│   ├── PayOrderService.java<br>│   └── port<br>│       ├── OrderStore.java<br>│       └── PaymentGateway.java<br>└── adapter<br>    ├── web<br>    │   └── OrderController.java<br>    ├── persistence<br>    │   └── JpaOrderStore.java<br>    └── payment<br>        ├── MomoPaymentAdapter.java<br>        └── OrangeMoneyPaymentAdapter.java</pre><p>domain and application are the core. adapter is everything that touches the outside world.</p><h3>The domain: where the rules live</h3><pre>public class Order {<br><br>    private final Long id;<br>    private final long amount;<br>    private OrderStatus status;<br><br>    public Order(Long id, long amount, OrderStatus status) {<br>        this.id = id;<br>        this.amount = amount;<br>        this.status = status;<br>    }<br><br>    public void ensurePayable() {<br>        if (status == OrderStatus.PAID) {<br>            throw new IllegalStateException(&quot;Order &quot; + id + &quot; is already paid&quot;);<br>        }<br>    }<br><br>    public void markPaid() {<br>        ensurePayable();<br>        status = OrderStatus.PAID;<br>    }<br><br>    public Long id() { return id; }<br>    public long amount() { return amount; }<br>    public OrderStatus status() { return status; }<br>}</pre><p>The rule “an order can’t be paid twice” now lives in exactly one place.</p><h3>The ports: what the core needs</h3><pre>public interface OrderStore {<br>    Optional&lt;Order&gt; findById(Long id);<br>    void save(Order order);<br>}</pre><pre>public interface PaymentGateway {<br>    Provider provider();<br>    PaymentResult charge(String phone, long amount, String reference);<br>}</pre><p>Notice the names. OrderStore, not OrderJpaRepository. PaymentGateway, not MomoClient. Ports speak the language of the business, not of the tools.</p><h3>The service: the core’s use case</h3><pre>public class PayOrderService {<br><br>    private final OrderStore orders;<br>    private final Map&lt;Provider, PaymentGateway&gt; gateways;<br>    <br>    public PayOrderService(OrderStore orders, List&lt;PaymentGateway&gt; gateways) {<br>        this.orders = orders;<br>        this.gateways = gateways.stream()<br>            .collect(Collectors.toMap(PaymentGateway::provider, g -&gt; g));<br>    }<br>    <br>    public void pay(Long orderId, Provider provider, String phone) {<br>        Order order = orders.findById(orderId)<br>            .orElseThrow(() -&gt; new OrderNotFoundException(orderId));<br>        order.ensurePayable();<br>        PaymentGateway gateway = gateways.get(provider);<br>        if (gateway == null) {<br>            throw new UnsupportedProviderException(provider);<br>        }<br>        PaymentResult result = gateway.charge(phone, order.amount(), &quot;order-&quot; + orderId);<br>        if (!result.successful()) {<br>            throw new PaymentFailedException(result.reason());<br>        }<br>        order.markPaid();<br>        orders.save(order);<br>    }<br>}</pre><p>Read it again and look for MoMo, Orange Money, SQL or HTTP. They aren’t there. This class describes how paying for an order works, and nothing else.</p><h3>The adapters: plugging in real tools</h3><p>Each payment provider gets its own adapter:</p><pre>@Component<br>public class MomoPaymentAdapter implements PaymentGateway {<br>    <br>    private final RestClient momoClient;<br>    public MomoPaymentAdapter(RestClient momoClient) {<br>        this.momoClient = momoClient;<br>    }<br>    @Override<br>    public Provider provider() {<br>        return Provider.MTN_MOMO;<br>    }<br>    @Override<br>    public PaymentResult charge(String phone, long amount, String reference) {<br>        // Everything MoMo-specific lives here and only here:<br>        // its request format, headers, authentication and status codes.<br>        // Translate MoMo&#39;s answer into the core&#39;s PaymentResult.<br>    }<br>}</pre><p>OrangeMoneyPaymentAdapter looks the same, with Orange&#39;s details inside. The database gets an adapter too:</p><pre>@Component<br>public class JpaOrderStore implements OrderStore {<br>    <br>    private final OrderJpaRepository jpa;<br>    public JpaOrderStore(OrderJpaRepository jpa) {<br>        this.jpa = jpa;<br>    }<br>    @Override<br>    public Optional&lt;Order&gt; findById(Long id) {<br>        return jpa.findById(id).map(OrderEntity::toDomain);<br>    }<br>    @Override<br>    public void save(Order order) {<br>        jpa.save(OrderEntity.fromDomain(order));<br>    }<br>}</pre><p>OrderEntity is the class with the @Entity annotations. It stays in the adapter, so JPA never leaks into the domain.</p><p>Finally, the controller is an inbound adapter. It turns HTTP into a call to the core:</p><pre>@RestController<br>@RequestMapping(&quot;/orders&quot;)<br>public class OrderController {<br><br>    private final PayOrderService payOrder;<br><br>    public OrderController(PayOrderService payOrder) {<br>        this.payOrder = payOrder;<br>    }<br><br>    @PostMapping(&quot;/{id}/pay&quot;)<br>    public ResponseEntity&lt;Void&gt; pay(@PathVariable Long id, @Valid @RequestBody PayRequest request) {<br>        payOrder.pay(id, request.provider(), request.phone());<br>        return ResponseEntity.noContent().build();<br>    }<br>}</pre><h3>Wiring it together</h3><p>The core has no Spring annotations, so we create the service in a configuration class:</p><pre>@Configuration<br>class OrderConfig {<br>    @Bean<br>    PayOrderService payOrderService(OrderStore orders, List&lt;PaymentGateway&gt; gateways) {<br>        return new PayOrderService(orders, gateways);<br>    }<br>}</pre><p>Spring finds every class that implements PaymentGateway and passes them all in. When the shop adds a third provider, you write one new adapter class. The service, the domain and the controller don&#39;t change at all.</p><h3>When it’s overkill</h3><p>Hexagonal architecture costs something: more files, more interfaces, and mapping between domain objects and database entities. For some apps, that cost buys nothing.</p><p>Skip it when the app is mostly CRUD. If your “business logic” is “save the form, show the list”, there’s nothing in the core to protect. A controller, a service and a Spring Data repository are the right size.</p><p>Use it when:</p><ul><li>The rules are real and expensive to get wrong: payments, bookings, pricing, anything with money or limits.</li><li>The outside world keeps changing: new payment providers, a new database, a mobile app joining the web app, a Kafka listener next to the REST API.</li><li>You want fast tests for the logic that matters most.</li></ul><p>You don’t have to apply it everywhere. Many teams use it only for the modules with real rules, like payments, and keep simple CRUD modules simple. That fits well inside a modular monolith: each module picks the structure it needs.</p><h3>Same idea, other names</h3><p>You may have heard of Onion Architecture or Clean Architecture. They draw different shapes and add their own layers, but they share one rule with hexagonal: business rules in the centre, frameworks and tools on the outside, and dependencies pointing inward. Learn that rule and you understand all three.</p><h3>The takeaway</h3><p>Tools change. This year it’s MoMo and PostgreSQL. Next year it might be a new payment provider, a new database, or a mobile app nobody planned for. The rules of your business change far less often.</p><p>Hexagonal architecture keeps those two apart. The rules sit in the middle and say what they need. Adapters on the edges plug in whatever tools you use today. When a tool changes, you swap an adapter, the way you swap a plug when you travel.</p><p>A simple test tells you if you’ve got it right: can you test your most important business rule without starting Spring, a database, or the network? If yes, then your core is free.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9a9c4e941d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OWASP Top 10: The Ten Ways Apps Get Broken]]></title>
            <link>https://medium.com/@awaprecious3t/owasp-top-10-the-ten-ways-apps-get-broken-7837c928bd7e?source=rss-9e0881aa60c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7837c928bd7e</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Awa precious]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 10:20:09 GMT</pubDate>
            <atom:updated>2026-11-05T10:20:09.885Z</atom:updated>
            <content:encoded><![CDATA[<p>Nov 5, 2026 · @PCodes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7owaGM5o03xtcYwIcmq9Q.png" /></figure><p>A customer orders a phone online. To track it, they open this page:</p><pre>https://shop.example.com/orders/1042</pre><p>Out of curiosity, they change 1042 to 1043 and press Enter. The page loads someone else’s order: their name, phone number, home address, and what they bought.</p><p>No hacking tool needed. No special skill either. Just one number changed in the address bar.</p><p>This is the most common security flaw in web applications today. It sits at number one on a list every developer should know: the OWASP Top 10. This article walks through all ten, each with an everyday picture, a real example, and what to do about it in Spring Boot.</p><h3>What OWASP is</h3><p>OWASP, the Open Worldwide Application Security Project, is a non-profit that helps developers build safer software. Its best-known work is the Top 10: a ranked list of the most common and damaging ways web applications get broken.</p><p>The list isn’t anyone’s opinion. OWASP collects data from security teams that test real applications, then ranks problems by how often they appear and how much harm they do. The newest edition, the Top 10:2025, was presented in November 2025 and finalised in January 2026. It replaced the 2021 edition.</p><p>Think of it as a list of the ten most common ways burglars get into houses. Knowing it won’t make your house unbreakable. But if you lock those ten doors, most burglars will go next door.</p><h3>1. Broken Access Control</h3><p>Imagine a hotel where your key card opens every room on your floor. The lock works. It just never checks whether the room is yours.</p><p>That’s the order page from the opening. The app checked that the customer was logged in. It never checked whether order 1043 belonged to them. Logged in and allowed are two different questions, and the app only asked the first.</p><p>The fix is to ask both questions on every request:</p><pre>@GetMapping(&quot;/orders/{id}&quot;)<br>public OrderResponse getOrder(@PathVariable Long id,<br>                              @AuthenticationPrincipal CustomerPrincipal me) {<br>    Order order = orderRepository.findByIdAndCustomerId(id, me.id())<br>        .orElseThrow(() -&gt; new ResponseStatusException(HttpStatus.NOT_FOUND));<br>    return OrderResponse.from(order);<br>}</pre><p>The query only finds the order if it belongs to the logged-in customer. Someone else’s order returns 404 Not Found, not 403 Forbidden. A 403 would confirm the order exists, which tells an attacker which IDs are worth trying.</p><h3>2. Security Misconfiguration</h3><p>A shop owner has a steel front door, but leaves the back door open every night.</p><p>In apps, the back doors are settings: an admin account still using its default password, a debug page left on in production, or error pages that show the full stack trace to anyone. It’s so common that analyses of the 2025 data report some form of misconfiguration in every application tested.</p><p>In Spring Boot, the usual suspects are Actuator and error details. Boot is safe by default, exposing only the health endpoint over the web. The danger is a developer who sets everything to visible while debugging and never changes it back. For production:</p><pre>management.endpoints.web.exposure.include=health<br>server.error.include-stacktrace=never<br>server.error.include-message=never</pre><p>Also change every default password, switch off Swagger UI in production unless it’s protected, and keep production settings in their own profile so a test setting can’t leak in.</p><h3>3. Software Supply Chain Failures</h3><p>A restaurant may have the cleanest kitchen in the World but if its supplier delivers spoiled meat, customers will still get sick.</p><p>Your app is mostly other people’s code. A typical Spring Boot project pulls in over a hundred libraries, and a MERN project often pulls in hundreds of npm packages. If one of them has a hole, or gets taken over by an attacker who pushes a poisoned update, that hole is now in your app. Log4Shell in 2021 is the famous case: one flaw in a logging library put a huge share of the world’s Java applications at risk overnight.</p><p>What helps:</p><ul><li>Use only well-known libraries you actually need. Every dependency is someone you trust with your users’ data.</li><li>Turn on Dependabot or Renovate so you hear about security updates and apply them.</li><li>Add the OWASP Dependency-Check plugin to your Maven or Gradle build, so it fails when a library has a known vulnerability.</li><li>For Node projects, commit package-lock.json and use npm ci in your build, so the exact versions you tested are the ones that ship.</li></ul><h3>4. Cryptographic Failures</h3><p>Writing your PIN on the back of your bank card. The card has protection, and you’ve undone it.</p><p>The classic example is storing passwords as plain text, or hashed with a fast algorithm like MD5 or SHA-256. When the database leaks, and databases do leak, attackers read the passwords directly or crack them in hours. Because people reuse passwords, the damage spreads to their email and bank accounts too.</p><p>Spring Security makes the right choice one line:</p><pre>@Bean<br>PasswordEncoder passwordEncoder() {<br>    return PasswordEncoderFactories.createDelegatingPasswordEncoder();<br>}</pre><p>This uses BCrypt by default. It’s slow on purpose, so guessing billions of passwords becomes impractical.</p><p>The same category covers sending data without HTTPS, putting secrets like API keys in your Git repository, and storing data you don’t need. The safest card number is the one you never saved.</p><h3>5. Injection</h3><p>A bank form asks for your name. You write: “John. Also, transfer all the money in this branch to account 5521.” A careless clerk reads the whole line aloud as an instruction.</p><p>That’s injection: the app treats what the user typed as a command. The classic version is SQL:</p><pre>// Dangerous: user input becomes part of the SQL<br>String sql = &quot;SELECT * FROM users WHERE email = &#39;&quot; + email + &quot;&#39;&quot;;<br>List&lt;Map&lt;String, Object&gt;&gt; users = jdbcTemplate.queryForList(sql);</pre><p>If someone types &#39; OR &#39;1&#39;=&#39;1 as their email, the query becomes &quot;give me every user&quot;. The fix is to pass input as a parameter, never as part of the text:</p><pre>// Safe: the database treats the input as data, never as SQL<br>List&lt;Map&lt;String, Object&gt;&gt; users =<br>    jdbcTemplate.queryForList(&quot;SELECT * FROM users WHERE email = ?&quot;, email);</pre><p>Spring Data methods like findByEmail and @Query with :email parameters are safe. The danger is string concatenation, in SQL or JPQL alike.</p><p>MERN apps have their own version. Pass req.body straight into a MongoDB query, and a login request with {&quot;password&quot;: {&quot;$ne&quot;: null}} means &quot;any password that isn&#39;t empty&quot;. Validate that inputs are plain strings before they reach the query.</p><h3>6. Insecure Design</h3><p>A bank fits excellent locks, then lets anyone reset your PIN over the phone if they know your date of birth. Every lock works. The plan is broken.</p><p>Insecure design isn’t a coding mistake. The code does exactly what it was designed to do, and the design never asked “how could someone abuse this?” Some examples:</p><ul><li>An OTP check with no attempt limit, so a script can try all 10,000 codes.</li><li>A “forgot password” form that says “no account with this email”, which tells attackers which emails are registered.</li><li>A promo code that can be applied again and again to the same order.</li></ul><p>No amount of clean code fixes a broken plan. The fix happens before coding: for every feature, ask how a dishonest user would use it. The rate limiting and idempotency articles in this series are both answers to that question.</p><h3>7. Authentication Failures</h3><p>A front door whose lock accepts “1234”, lets you try as many keys as you like, and hands out keys that never stop working.</p><p>Authentication is how an app checks who you are. It fails when:</p><ul><li>Users can choose passwords like 123456.</li><li>Login allows unlimited attempts.</li><li>Login tokens never expire, or stay valid after the user logs out or changes their password.</li><li>Admin accounts have no second factor, so one stolen password opens everything.</li></ul><p>In Spring Boot, keep access tokens short-lived, such as 15 minutes, with a refresh token that you can revoke. Rate-limit the login endpoint. Check new passwords against a list of known leaked passwords. And require a second factor for anyone who can see other people’s data.</p><h3>8. Software or Data Integrity Failures</h3><p>A delivery arrives with a broken seal. You sign for it anyway and put it on the shelf.</p><p>This category is about trusting data or code without checking it has not been changed. The most common version in everyday apps is trusting what the client sends:</p><pre>// Dangerous: the client decides what the order costs<br>order.setTotal(request.total());<br><br>// Safe: the server works it out from its own data<br>Product product = productRepository.findById(request.productId()).orElseThrow();<br>order.setTotal(product.getPrice() * request.quantity());</pre><p>Anyone can edit a request with free tools. If the app accepts the price it’s given, a 150,000 FCFA phone costs whatever the attacker types.</p><p>Payment callbacks are another big one. When a payment provider calls your server to say “payment successful”, check the signature or confirm with the provider’s API before you ship anything. Otherwise anyone who finds your callback URL can send a fake success message.</p><h3>9. Logging and Alerting Failures</h3><p>A shop installs CCTV cameras, but they record nothing, and nobody even watches the screens.</p><p>Many breaches are discovered months after they happen, and often by someone outside the company: a customer, a researcher, or a journalist. Usually the evidence was there the whole time: 5,000 failed logins in one night, or one account downloading every customer record. Nobody was looking.</p><p>Log the events that matter for security: logins that succeed and fail, refused access, password and email changes, and admin actions. Record who, when and from where:</p><pre>log.warn(&quot;Login failed user={} ip={}&quot;, username, request.getRemoteAddr());</pre><p>Never log passwords, OTPs, tokens or card numbers. Then set up alerts, so a sudden spike in failures wakes someone up instead of sitting quietly in a file.</p><h3>10. Mishandling of Exceptional Conditions</h3><p>An ATM’s network drops in the middle of a withdrawal. Unsure what to do, it hands out the cash anyway.</p><p>This category is new in 2025. It covers what your code does when something unexpected happens: a service is down, a timeout fires, or an input breaks an assumption. The dangerous pattern is failing open, where an error leads to “allow”:</p><pre>// Dangerous: if the check itself breaks, the user gets through<br>boolean blocked;<br>try {<br>    blocked = fraudService.isBlocked(userId);<br>} catch (Exception e) {<br>    blocked = false;<br>}</pre><p>If the fraud service goes down, every blocked user is suddenly allowed. Attackers love this, because crashing a service is often easier than beating it.</p><p>The rule is to fail closed. If you can’t confirm something is safe, refuse and tell the user to try again. Handle errors in one place with @RestControllerAdvice, return clean error responses, and never show stack traces to users.</p><h3>The takeaway</h3><p>Read the list again and notice how few of these need a genius attacker. Changing a number in a URL. Typing a quote mark into a form. Editing a price in a request. Waiting for a service to go down.</p><p>Most real breaches aren’t clever. They walk through a check that was never written. And checks are cheap: one extra condition in a query, one line in a config file, one question asked at design time.</p><p>You don’t need to memorise the list. Keep one habit: for every feature you build, ask “what happens if the person using this is dishonest?” Those ten categories are the most common answers to that question.</p><h3>Sources</h3><ul><li><a href="https://owasp.org/Top10/2025/">OWASP Top 10:2025, official site</a></li><li><a href="https://cloudinsight.cc/en/blog/owasp-top-10">OWASP Top 10:2025 explained, with 2021 vs 2025 changes (CloudInsight)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7837c928bd7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rate Limiting: Why the App Says “Too Many Attempts”]]></title>
            <link>https://medium.com/@awaprecious3t/rate-limiting-why-the-app-says-too-many-attempts-9fe02ead1778?source=rss-9e0881aa60c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fe02ead1778</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Awa precious]]></dc:creator>
            <pubDate>Wed, 04 Nov 2026 14:21:38 GMT</pubDate>
            <atom:updated>2026-11-04T14:21:38.718Z</atom:updated>
            <content:encoded><![CDATA[<p>Nov 4, 2026 · @PCodes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xq5VAeT-9vtHNXnlkEBN8Q.png" /></figure><p>You’ve surely seen this screen before. You type the wrong code three times and the app says: “Too many attempts. Try again in 15 minutes.”</p><p>It’s annoying when it happens to you right?. Here’s why it exists.</p><p>A 4-digit OTP has 10,000 possible values, from 0000 to 9999. A short script can send 10 guesses per second to a login endpoint. Without any limit, it tries every possible code in about 17 minutes. Most codes are found in half that time.</p><p>Now add one rule: three wrong attempts per code. The attacker’s chance of guessing right drops to 3 in 10,000. That’s 0.03%. The same script that would have broken into the account now fails almost every time.</p><p>That rule is rate limiting. It’s one of the cheapest security features you can build, and one of the most important.</p><h3>What rate limiting is</h3><p>Rate limiting means capping how many times someone can do something within a period of time.</p><p>You already live with it. An ATM keeps your card after three wrong PINs. A bank teller serves one customer at a time, and the queue controls how fast people reach the counter. A shop may put “maximum 2 per customer” on a product so one person can’t buy the whole shelf.</p><p>Apps use the same idea for four reasons:</p><ul><li><strong>Stopping guessing attacks.</strong> OTPs, PINs and passwords are only safe if attackers can’t try them all. Rate limiting makes trying them all impossible.</li><li><strong>Controlling cost.</strong> Every OTP your app sends by SMS costs you money. Without a limit, one script can request thousands of codes and give you a crazy bill.</li><li><strong>Keeping the server alive.</strong> A buggy app stuck in a retry loop, or one heavy user, can use up your server’s capacity. A limit keeps one client from slowing everyone else down.</li><li><strong>Fairness.</strong> On a shared API, a limit makes sure every customer gets their share.</li></ul><p>The user rarely notices a good rate limit. They notice when it’s missing: the account gets hacked, the SMS bill explodes, or the app goes down at the worst moment.</p><h3>Three ways to count</h3><p>Every rate limiter answers one question: has this person done too much recently? There are three common ways to count “recently”.</p><h3>Fixed window</h3><p>Split time into blocks, such as one minute each, and count the number of requests per block. When the minute ends, the counter resets to zero.</p><p>Imagine a buffet that allows you to take 5 plates every hour. At the beginning of a new hour, your plate count resets.</p><p>It’s the simplest to build. Its weakness is the boundary. With a limit of 5 per minute, someone can send 5 requests at 12:59:58 and 5 more at 13:00:01. That makes 10 requests in 3 seconds, which is double the limit.</p><h3>Sliding window</h3><p>Imagine you have a rule:</p><p>A user can make a maximum of 5 requests every 60 seconds.</p><p>Instead of dividing time into fixed 60-seconds blocks, you always look at the last 60 seconds from the current moment.</p><h3>Token bucket</h3><p>Picture a bucket that holds 10 tokens. Every request takes one token. If the bucket is empty, the request is refused. Tokens drip back in at a steady rate, say one every 6 seconds.</p><p>This matches how people actually use apps. A user who opens the app fires off several requests at once. The bucket allows that burst. Someone hammering the API all day is held to the refill rate.</p><p>Token bucket is what most API gateways and libraries use for general traffic. Fixed windows are fine for simple rules like “3 OTP attempts”, where the boundary trick doesn’t matter much.</p><h3>Protecting OTPs in Spring Boot</h3><p>An OTP flow needs two limits:</p><ul><li><strong>Verifying:</strong> 3 wrong attempts per phone number, then a 15-minute wait. This stops guessing.</li><li><strong>Sending:</strong> 3 codes per phone number per hour. This stops someone running up your SMS bill.</li></ul><p>Both are fixed windows, and Redis is the right place for the counter. It’s shared by all your app instances, it counts atomically, and it deletes the counter for you when the window ends.</p><h3>The limiter</h3><pre>@Component<br>public class FixedWindowRateLimiter {<br>  <br>    private final StringRedisTemplate redis;<br>    public FixedWindowRateLimiter(StringRedisTemplate redis) {<br>        this.redis = redis;<br>    }<br>    public Decision check(String key, int limit, Duration window) {<br>        redis.opsForValue().setIfAbsent(key, &quot;0&quot;, window);<br>        long count = redis.opsForValue().increment(key);<br>        if (count &lt;= limit) {<br>            return Decision.allowed();<br>        }<br>        long secondsLeft = redis.getExpire(key, TimeUnit.SECONDS);<br>        return Decision.blocked(Duration.ofSeconds(Math.max(secondsLeft, 1)));<br>    }<br>    public void reset(String key) {<br>        redis.delete(key);<br>    }<br>    public record Decision(boolean allowed, Duration retryAfter) {<br>        static Decision allowed() { return new Decision(true, Duration.ZERO); }<br>        static Decision blocked(Duration wait) { return new Decision(false, wait); }<br>    }<br>}</pre><p>Here’s what each step does:</p><ol><li>setIfAbsent creates the counter at 0 with an expiry, but only if it doesn&#39;t exist yet. This starts a new window.</li><li>increment adds one and returns the new count. Redis does this atomically, so two requests arriving together can&#39;t both read 2 and both write 3. That&#39;s the race condition article again.</li><li>If the count is over the limit, getExpire tells us how long until the window ends, so we can tell the user exactly how long to wait.</li></ol><h3>Using it</h3><pre>@RestController<br>@RequestMapping(&quot;/otp&quot;)<br>public class OtpController {<br>    <br>    private final FixedWindowRateLimiter limiter;<br>    private final OtpService otpService;<br>    public OtpController(FixedWindowRateLimiter limiter, OtpService otpService) {<br>        this.limiter = limiter;<br>        this.otpService = otpService;<br>    }<br>    @PostMapping(&quot;/send&quot;)<br>    public ResponseEntity&lt;Void&gt; send(@Valid @RequestBody SendOtpRequest request) {<br>        var decision = limiter.check(&quot;otp:send:&quot; + request.phone(), 3, Duration.ofHours(1));<br>        if (!decision.allowed()) {<br>            return tooManyRequests(decision.retryAfter());<br>        }<br>        otpService.send(request.phone());<br>        return ResponseEntity.accepted().build();<br>    }<br>    @PostMapping(&quot;/verify&quot;)<br>    public ResponseEntity&lt;Void&gt; verify(@Valid @RequestBody VerifyOtpRequest request) {<br>        String key = &quot;otp:verify:&quot; + request.phone();<br>        var decision = limiter.check(key, 3, Duration.ofMinutes(15));<br>        if (!decision.allowed()) {<br>            return tooManyRequests(decision.retryAfter());<br>        }<br>        otpService.verify(request.phone(), request.code());<br>        limiter.reset(key);<br>        return ResponseEntity.noContent().build();<br>    }<br>    private ResponseEntity&lt;Void&gt; tooManyRequests(Duration wait) {<br>        return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS)<br>            .header(HttpHeaders.RETRY_AFTER, String.valueOf(wait.toSeconds()))<br>            .build();<br>    }<br>}</pre><p>Two details are easy to miss.</p><p>First, the limit is checked before the code. Once someone is blocked, even the correct code is refused. An attacker gains nothing by guessing during the wait, because they can’t tell a right guess from a wrong one.</p><p>Second, a successful verification resets the counter. Otherwise a user who mistyped twice, then logged in, would start their next login with only one attempt left.</p><p>The key uses the phone number, not the user’s IP address. We’ll see why that matters shortly.</p><h3>General API limits with a token bucket</h3><p>OTPs are a special case. For the rest of your API, you want something like “100 requests per minute per user, with room for short bursts”. That’s a token bucket.</p><p>Bucket4j is the standard Java library for it:</p><pre>@Component<br>public class ApiRateLimitFilter extends OncePerRequestFilter {<br><br>    private final Map&lt;String, Bucket&gt; buckets = new ConcurrentHashMap&lt;&gt;();<br>      @Override<br>     protected void doFilterInternal(HttpServletRequest request,<br>                                    HttpServletResponse response,<br>                                    FilterChain chain) throws ServletException, IOException {<br>        String client = clientKey(request);<br>        Bucket bucket = buckets.computeIfAbsent(client, key -&gt; newBucket());<br>        ConsumptionProbe probe = bucket.tryConsumeAndReturnRemaining(1);<br>        if (probe.isConsumed()) {<br>            response.setHeader(&quot;X-RateLimit-Remaining&quot;, String.valueOf(probe.getRemainingTokens()));<br>            chain.doFilter(request, response);<br>            return;<br>        }<br>        long waitSeconds = Math.max(1, TimeUnit.NANOSECONDS.toSeconds(probe.getNanosToWaitForRefill()));<br>        response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());<br>        response.setHeader(HttpHeaders.RETRY_AFTER, String.valueOf(waitSeconds));<br>    }<br>    private Bucket newBucket() {<br>        Bandwidth limit = Bandwidth.builder()<br>            .capacity(100)<br>            .refillGreedy(100, Duration.ofMinutes(1))<br>            .build();<br>        return Bucket.builder().addLimit(limit).build();<br>    }<br>    private String clientKey(HttpServletRequest request) {<br>        Authentication auth = SecurityContextHolder.getContext().getAuthentication();<br>        if (auth != null &amp;&amp; auth.isAuthenticated() &amp;&amp; !(auth instanceof AnonymousAuthenticationToken)) {<br>            return &quot;user:&quot; + auth.getName();<br>        }<br>        return &quot;ip:&quot; + request.getRemoteAddr();<br>    }<br>}</pre><p>The bucket holds 100 tokens and refills 100 per minute, gradually. A user can open the app and fire 30 requests at once without trouble. A script sending requests nonstop is held to about 100 a minute.</p><p>This version keeps buckets in memory, which has two problems in production. Each app instance has its own buckets, so with three instances a user effectively gets 300 a minute. And the map grows with every new client and never shrinks. Bucket4j has Redis-backed versions that fix both. Use one once you run more than one instance.</p><h3>Getting the details right</h3><h3>Who are you limiting?</h3><p>The key you count against matters more than the algorithm.</p><ul><li><strong>By IP address</strong> is the obvious choice, and often the wrong one. Mobile networks put thousands of customers behind a small number of public IP addresses. Limit by IP, and one busy afternoon at a university can block every student on the same network. Attackers, meanwhile, can rotate through many IPs cheaply.</li><li><strong>By user or account</strong> is better once someone is logged in. It follows the person, not the network.</li><li><strong>By the thing being protected</strong> is best for sensitive actions. The OTP limiter counts per phone number, so it doesn’t matter how many devices or IPs the attacker uses.</li></ul><p>In practice you combine them. A generous per-IP limit stops floods from one place. A per-user limit keeps usage fair. A strict per-target limit protects OTPs, PINs and passwords.</p><p>One trap if your app runs behind Nginx or a load balancer: request.getRemoteAddr() returns the proxy&#39;s address, so every user looks like the same client. Set server.forward-headers-strategy=native so Spring reads the real client address from the X-Forwarded-For header. Only trust that header when it&#39;s set by your own proxy, because clients can fake it.</p><h3>Don’t let the limit become the attack</h3><p>If three wrong codes lock a phone number for 15 minutes, an attacker can lock someone out on purpose by sending three wrong codes every 15 minutes. The victim can never log in.</p><p>Ways to soften this:</p><ul><li>Tie verify attempts to the code itself, not just the phone number. Requesting a new code starts fresh, while sending codes stays limited per hour.</li><li>Increase the wait step by step, from 1 minute to 5 to 15, instead of jumping straight to a long block.</li><li>Alert your team when one number gets blocked repeatedly. That’s an attack in progress.</li></ul><h3>Tell the user what’s happening</h3><p>The correct HTTP response is 429 Too Many Requests with a Retry-After header giving the seconds to wait.</p><p>The app should turn that into a clear message: “Too many attempts. Try again in 12 minutes.” Not “Something went wrong.” A user who knows how long to wait will wait. A user who sees a vague error will tap again and again, and make it worse.</p><h3>Where to put it</h3><p>Rate limiting can live at different layers:</p><ul><li><strong>At the edge</strong> (Nginx, Cloudflare, an API gateway): rough per-IP limits that stop floods before they reach your app.</li><li><strong>In the app</strong>: limits that need business knowledge, like “3 OTP attempts per phone” or “free plan gets 1,000 calls a day”.</li></ul><p>Most serious systems use both.</p><h3>The takeaway</h3><p>The next time an app tells you to wait 15 minutes, it’s protecting your account from someone with a script and a lot of patience.</p><p>If you build APIs, look at every endpoint that checks a secret, sends a message, or costs you money. Ask: what happens if someone calls this 10,000 times? If the answer is “they get in” or “we pay for it”, that endpoint needs a limit before it goes live.</p><p>It’s a counter and an expiry. It’s one of the cheapest protections you’ll ever build.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fe02ead1778" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Idempotency: Making the Second Request Harmless]]></title>
            <link>https://medium.com/@awaprecious3t/idempotency-making-the-second-request-harmless-63d95af8741f?source=rss-9e0881aa60c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/63d95af8741f</guid>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Awa precious]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 08:19:59 GMT</pubDate>
            <atom:updated>2026-11-03T08:21:41.465Z</atom:updated>
            <content:encoded><![CDATA[<p>Nov 3, 2026 · @PCodes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRU6rWLP0CO5r13eu9rW2Q.png" /><figcaption>The Backend Engineering Series: Idempotency</figcaption></figure><p>A customer pays 15,000 FCFA for an order using mobile money. Your server receives the request, charges their wallet, and saves the order. Then it sends the response back, but the response never arrives. The customer’s network dropped for two seconds. The app sees a timeout and does what apps normally do: it tries again.</p><p>Your server receives a brand new request. It charges the wallet again and saves a second order. The customer has paid 30,000 FCFA for one pair of shoes, and they will tell everyone they know.</p><p>The server did nothing wrong by its own logic. The client did nothing wrong either. A timeout tells the client “I don’t know what happened”, and retrying is the only sensible response. The problem is that your endpoint can’t tell a retry from a new purchase.</p><p>Idempotency fixes that.</p><h3>What idempotency means</h3><p>An operation is idempotent when doing it once or doing it ten times leaves the system in the same state.</p><p>A light switch with separate “on” and “off” buttons is idempotent. Press “on” five times and the light is on. A toggle button is not. Press it five times and the result depends on where you started.</p><p>HTTP already defines which methods should behave this way:</p><ul><li><strong>GET</strong> reads data. Calling it twice changes nothing.</li><li><strong>PUT</strong> replaces a resource with what you send. PUT /users/42 {&quot;name&quot;: &quot;John&quot;} sets the name to John, however many times you send it.</li><li><strong>DELETE</strong> removes a resource. The first call deletes it. The second finds nothing to delete. The state is the same: the resource is gone.</li><li><strong>POST</strong> creates something new. Two calls create two things. POST is not idempotent.</li><li><strong>PATCH</strong> depends on what it does. {&quot;name&quot;: &quot;John&quot;} is idempotent. {&quot;balance&quot;: &quot;+500&quot;} is not.</li></ul><p>Idempotency is about the state of the server, not the response. The second DELETE may return 404 instead of 204. That&#39;s fine, as long as nothing else changed.</p><p>If you design your PUT and DELETE endpoints correctly, clients can retry them freely. The trouble is that the operations people care most about, like payments, orders and sign-ups, are POSTs.</p><h3>Why a duplicate check isn’t enough</h3><p>The first instinct is to look for a recent identical order:</p><pre>if (orderRepository.existsByCustomerAndAmountAndCreatedAtAfter(<br>        customerId, amount, Instant.now().minusSeconds(60))) {<br>    throw new DuplicateOrderException();<br>}</pre><p>This fails in three ways.</p><ul><li><strong>It blocks real purchases.</strong> A customer who buys two airtime top-ups of 1,000 FCFA in a minute gets the second one rejected.</li><li><strong>It guesses.</strong> “Same amount within 60 seconds” is a rule you invented. A retry after 61 seconds goes through.</li><li><strong>It races.</strong> It’s a check-then-act, the exact pattern from the race conditions article. Two retries arriving together both pass the check.</li></ul><p>The server can’t reliably tell a retry from a new request by looking at the request’s content. Only the client knows whether it means “do this again” or “I’m asking about the same thing”. So the client has to say so.</p><h3>How idempotency keys work</h3><p>The client generates a unique ID for each action the user takes, usually a UUID, and sends it in a header:</p><pre>POST /payments<br>Idempotency-Key: 9b2f6c1e-4a7d-4e3b-8c5a-1f0e2d3c4b5a<br>Content-Type: application/json</pre><pre>{ &quot;orderId&quot;: 1042, &quot;amount&quot;: 15000, &quot;phone&quot;: &quot;6XXXXXXXX&quot; }</pre><p>The rule for the client is simple: one key per user action, reused on every retry of that action. If the user taps “Pay” once and the app retries three times, all four requests carry the same key. If the user buys something else, that’s a new key.</p><p>The server then follows these steps:</p><ol><li>Look up the key.</li><li><strong>Not found:</strong> save the key with status PROCESSING, run the operation, then store the response with status COMPLETED.</li><li><strong>Found and </strong><strong>COMPLETED:</strong> don&#39;t run anything. Return the stored response, the same status code and the same body.</li><li><strong>Found and </strong><strong>PROCESSING:</strong> the first request is still running. Return 409 Conflict and tell the client to try again shortly.</li></ol><p>The customer from the opening now gets one charge and one order. Their retry receives the response the first request was trying to deliver.</p><p>This isn’t a niche pattern. Stripe has used an Idempotency-Key header for years, the MTN MoMo API asks for a unique X-Reference-Id on each payment request, and the IETF has a draft standardising the header name.</p><h3>Building it in Spring Boot</h3><h3>The table</h3><pre>CREATE TABLE idempotency_keys (<br>    customer_id      BIGINT       NOT NULL,<br>    idempotency_key  VARCHAR(64)  NOT NULL,<br>    request_hash     CHAR(64)     NOT NULL,<br>    status           VARCHAR(16)  NOT NULL,<br>    response_status  INT,<br>    response_body    JSONB,<br>    created_at       TIMESTAMPTZ  NOT NULL DEFAULT now(),<br>    PRIMARY KEY (customer_id, idempotency_key)<br>);</pre><p>The primary key does the important work. It guarantees that only one request can ever claim a given key for a given customer. That’s the lesson from race conditions again: the database makes the final decision, not an if statement.</p><p>request_hash lets us detect a client reusing a key for a different request. More on that in the edge cases.</p><h3>The store</h3><pre>@Repository<br>public class IdempotencyStore { </pre><pre>private final JdbcClient jdbc;<br>    public IdempotencyStore(JdbcClient jdbc) {<br>        this.jdbc = jdbc;<br>    }<br>    public boolean claim(long customerId, String key, String requestHash) {<br>        int inserted = jdbc.sql(&quot;&quot;&quot;<br>                INSERT INTO idempotency_keys (customer_id, idempotency_key, request_hash, status)<br>                VALUES (:customerId, :key, :hash, &#39;PROCESSING&#39;)<br>                ON CONFLICT DO NOTHING<br>                &quot;&quot;&quot;)<br>            .param(&quot;customerId&quot;, customerId)<br>            .param(&quot;key&quot;, key)<br>            .param(&quot;hash&quot;, requestHash)<br>            .update();<br>        return inserted == 1;<br>    }<br>    public Optional&lt;IdempotencyRecord&gt; find(long customerId, String key) {<br>        return jdbc.sql(&quot;&quot;&quot;<br>                SELECT request_hash, status, response_status, response_body::text AS response_body<br>                FROM idempotency_keys<br>                WHERE customer_id = :customerId AND idempotency_key = :key<br>                &quot;&quot;&quot;)<br>            .param(&quot;customerId&quot;, customerId)<br>            .param(&quot;key&quot;, key)<br>            .query(IdempotencyRecord.class)<br>            .optional();<br>    }<br>    public void complete(long customerId, String key, int status, String body) {<br>        jdbc.sql(&quot;&quot;&quot;<br>                UPDATE idempotency_keys<br>                SET status = &#39;COMPLETED&#39;, response_status = :status, response_body = CAST(:body AS jsonb)<br>                WHERE customer_id = :customerId AND idempotency_key = :key<br>                &quot;&quot;&quot;)<br>            .param(&quot;status&quot;, status)<br>            .param(&quot;body&quot;, body)<br>            .param(&quot;customerId&quot;, customerId)<br>            .param(&quot;key&quot;, key)<br>            .update();<br>    }<br>    public void release(long customerId, String key) {<br>        jdbc.sql(&quot;DELETE FROM idempotency_keys WHERE customer_id = :customerId AND idempotency_key = :key&quot;)<br>            .param(&quot;customerId&quot;, customerId)<br>            .param(&quot;key&quot;, key)<br>            .update();<br>    }<br>}<br>public record IdempotencyRecord(String requestHash, String status, Integer responseStatus, String responseBody) {}</pre><p>claim is the heart of it. INSERT ... ON CONFLICT DO NOTHING either inserts the row and returns 1, or finds the key already there and returns 0. It&#39;s one statement, so two simultaneous requests can&#39;t both get 1.</p><p>These methods are deliberately not wrapped in one big @Transactional. Each statement commits on its own, so the PROCESSING row is visible to other requests the moment it&#39;s claimed.</p><h3>The service</h3><pre>@Service<br>public class IdempotentPaymentService {</pre><pre>    private final IdempotencyStore store;<br>    private final PaymentService payments;<br>    private final ObjectMapper json;<br><br>    public IdempotentPaymentService(IdempotencyStore store, PaymentService payments, ObjectMapper json) {<br>        this.store = store;<br>        this.payments = payments;<br>        this.json = json;<br>    }<br><br><br>    public ResponseEntity&lt;PaymentResponse&gt; pay(long customerId, String key, PaymentRequest request) {<br>        String hash = sha256(toJson(request));<br>        if (!store.claim(customerId, key, hash)) {<br>            return replay(customerId, key, hash);<br>        }<br>        try {<br>            PaymentResponse response = payments.charge(customerId, key, request);<br>            store.complete(customerId, key, 201, toJson(response));<br>            return ResponseEntity.status(201).body(response);<br>        } catch (RuntimeException e) {<br>            store.release(customerId, key);<br>            throw e;<br>        }<br>    }<br><br><br>    private ResponseEntity&lt;PaymentResponse&gt; replay(long customerId, String key, String hash) {<br>        IdempotencyRecord record = store.find(customerId, key)<br>            .orElseThrow(RequestInProgressException::new);<br>        if (!record.requestHash().equals(hash)) {<br>            throw new IdempotencyKeyMismatchException();<br>        }<br>        if (record.status().equals(&quot;PROCESSING&quot;)) {<br>            throw new RequestInProgressException();<br>        }<br>        PaymentResponse body = fromJson(record.responseBody(), PaymentResponse.class);<br>        return ResponseEntity.status(record.responseStatus()).body(body);<br>    }<br>    <br>  <br>  private String toJson(Object value) {<br>        try {<br>            return json.writeValueAsString(value);<br>        } catch (JsonProcessingException e) {<br>            throw new IllegalStateException(e);<br>        }<br>    }<br>    <br><br>  private &lt;T&gt; T fromJson(String value, Class&lt;T&gt; type) {<br>        try {<br>            return json.readValue(value, type);<br>        } catch (JsonProcessingException e) {<br>            throw new IllegalStateException(e);<br>        }<br>    }<br>    <br><br><br>  private static String sha256(String value) {<br>        try {<br>            byte[] digest = MessageDigest.getInstance(&quot;SHA-256&quot;)<br>                .digest(value.getBytes(StandardCharsets.UTF_8));<br>            return HexFormat.of().formatHex(digest);<br>        } catch (NoSuchAlgorithmException e) {<br>            throw new IllegalStateException(e);<br>        }<br>    }<br>}</pre><p>Notice that the key is passed into payments.charge(...). We&#39;ll see why in the edge cases.</p><h3>The exceptions and the controller</h3><pre>@ResponseStatus(HttpStatus.CONFLICT)<br>public class RequestInProgressException extends RuntimeException {}<br><br><br><br>@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)<br>public class IdempotencyKeyMismatchException extends RuntimeException {}<br><br></pre><pre>@RestController<br>@RequestMapping(&quot;/payments&quot;)<br>public class PaymentController {<br><br>    private final IdempotentPaymentService service;<br>    public PaymentController(IdempotentPaymentService service) {<br>        this.service = service;<br>    }<br><br>    @PostMapping<br>    public ResponseEntity&lt;PaymentResponse&gt; pay(<br>            @RequestHeader(&quot;Idempotency-Key&quot;) String key,<br>            @AuthenticationPrincipal CustomerPrincipal customer,<br>            @Valid @RequestBody PaymentRequest request<br>    ) {<br>        return service.pay(customer.id(), key, request);<br>    }<br>}</pre><p>The header is required, so Spring rejects a payment request without one with 400 Bad Request. For a payment endpoint, that&#39;s what you want.</p><h3>The edge cases that matter</h3><h3>A retry arrives while the first request is still running</h3><p>Mobile money confirmations can take several seconds. A retry often lands before the first request finishes. The key exists with status PROCESSING, so the retry gets 409 Conflict.</p><p>Add a Retry-After: 2 header so the client knows to wait two seconds and try again. When it does, the first request has usually finished, and the retry gets the stored response.</p><p>The alternative is to make the retry wait for the first request to finish. That holds a server thread for the whole wait, and the client is about to time out again anyway. Returning 409 quickly is simpler.</p><h3>Same key, different request</h3><p>A buggy client sends key abc to pay 15,000 FCFA, then sends key abc again to pay 2,000 FCFA. If you return the stored response, the client thinks the 2,000 payment succeeded when it never happened.</p><p>That’s why we store request_hash. A mismatch returns 422 Unprocessable Entity. It tells the client developer they have a bug, instead of hiding it.</p><h3>The operation fails</h3><p>There are two kinds of failure, and they need different handling.</p><ul><li><strong>A clear business answer</strong>, such as “insufficient balance”. The result is final and nothing changed. Store it like a success. A retry with the same key gets the same 402 or 422 back. If the customer tops up and tries again, the app sends a new key, because it&#39;s a new attempt.</li><li><strong>An unexpected error</strong> before anything happened, such as the database refusing a connection. Release the key, as the service above does, so the retry can run the operation properly.</li></ul><p>In the code above, charge signals business failures by throwing, so they get released too. In a real project, catch your business exceptions separately and store their response with complete.</p><h3>The server crashes halfway</h3><p>This is the hard one. The server charges the customer’s wallet through the payment provider, then crashes before writing COMPLETED. The key sits at PROCESSING forever. Worse, if you released it on error, a retry would charge the customer a second time.</p><p>Two things protect you here:</p><ol><li><strong>Pass the key down to the provider.</strong> That’s why charge receives it. Use it, or a value derived from it, as the provider&#39;s reference, such as MoMo&#39;s X-Reference-Id. Now the provider can recognise the repeat too, and you can ask the provider &quot;what happened to this reference?&quot;</li><li><strong>Run a cleanup job</strong> that finds keys stuck at PROCESSING for more than a few minutes, asks the provider for the status of each, and marks them COMPLETED or releases them based on the answer.</li></ol><p>Idempotency at your API only protects your API. Every external call that moves money needs its own idempotent reference.</p><h3>Expiry</h3><p>You don’t need keys forever. Retries happen within minutes or hours. Delete keys older than 24 hours with a scheduled job:</p><pre>DELETE FROM idempotency_keys WHERE created_at &lt; now() - INTERVAL &#39;24 hours&#39;;</pre><h3>Scope</h3><p>The primary key includes customer_id, so keys belong to a customer. Without that, one customer could send another customer&#39;s key and receive their stored payment response. Always scope keys to the authenticated user.</p><h3>Redis or the database?</h3><p>You can store keys in Redis with SET key value NX EX 86400. It&#39;s fast and expires keys for you. The catch is that Redis and your orders table can disagree. If the order commits in PostgreSQL but the Redis write fails, the guarantee is gone.</p><p>When the protected operation writes to PostgreSQL, keep the keys in PostgreSQL. Reach for Redis when the protected operation doesn’t touch your database, or when you need to handle very high traffic and accept that trade-off.</p><h3>The takeaway</h3><p>Networks fail, and clients retry. You can’t stop either. What you control is whether the retry does damage.</p><p>For every endpoint that moves money, creates an order, or sends a message, ask: what happens if this exact request arrives twice? If the answer is “the customer pays twice”, the endpoint needs an idempotency key.</p><p>The pattern is small: one table, one INSERT ... ON CONFLICT, and a stored response. It&#39;s the difference between a timeout the customer never notices and a refund they have to ask for.</p><p>#BackendEngineering #SpringBoot #Java #APIDesign #Payments</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63d95af8741f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Race Conditions: When Two Requests Arrive at the Same Time]]></title>
            <link>https://medium.com/@awaprecious3t/race-conditions-when-two-requests-arrive-at-the-same-time-183c0c61d181?source=rss-9e0881aa60c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/183c0c61d181</guid>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Awa precious]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 11:22:47 GMT</pubDate>
            <atom:updated>2026-11-02T11:40:43.215Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yaVIRNkJwtRUgHChTWiW3Q.png" /></figure><p>Nov 2, 2026 · @PCodes</p><p>A user has 8,000 FCFA in their wallet. They tap “Withdraw 5,000” and the app feels slow, so they tap again. Two requests reach your server a few milliseconds apart.</p><p>Both requests read the balance: 8,000. Both check that 8,000 is enough for 5,000. Both approve. Both write the new balance: 3,000.</p><p>The user walked away with 10,000 FCFA from an account that held 8,000. Your database says they still have 3,000. No exception was thrown and nothing appeared in the logs. Every line of code did exactly what it was written to do.</p><p>That is a race condition.</p><h3>What a race condition is</h3><p>A race condition happens when two operations run at the same time, touch the same data, and the final result depends on which one gets there first.</p><p>Your Spring Boot app serves each request on its own thread. Tomcat allows up to 200 of them by default. When two requests touch the same row, you don’t decide who goes first. The thread scheduler and the database do. Most of the time the order doesn’t matter. When one request reads data that the other is about to change, the result is wrong.</p><p>A race needs three things:</p><ul><li><strong>Shared state</strong>: a database row, a cache key, a file, or a field inside a singleton bean.</li><li><strong>Concurrent access</strong>: two or more threads, server instances, or processes reaching that state.</li><li><strong>At least one write</strong>: if everyone only reads, nothing can go wrong.</li></ul><p>Take away any one of the three and the race disappears. Almost every fix in this article works on the second one. It either lets only one operation touch the data at a time, or it turns “read, decide, write” into a single step that can’t be split.</p><p>Node.js developers are not exempt. Node runs your JavaScript on one thread, but every await hands control to another request. Two requests can both read a document before either one saves it. Once you run more than one instance, you have real parallelism anyway.</p><h3>The two shapes you will meet</h3><p>Most race conditions in backend code take one of two forms.</p><h3>1. Lost update (read, modify, write)</h3><p>This is the wallet story in code:</p><pre>@Transactional<br>public void withdraw(Long accountId, long amount) {<br>    Account account = accountRepository.findById(accountId).orElseThrow();</pre><pre>    if (account.getBalance() &lt; amount) {<br>        throw new InsufficientFundsException();<br>    }</pre><pre>    account.setBalance(account.getBalance() - amount);<br>}</pre><p>It looks safe because of @Transactional. It isn&#39;t. PostgreSQL runs transactions at the Read Committed level by default. That level stops you from reading another transaction&#39;s uncommitted changes. It does not stop two transactions from reading the same committed value and then both acting on it.</p><p>Here is what happens when two withdrawals of 5,000 arrive together:</p><pre>Step   Request A                  Request B<br>----   ------------------------   ------------------------<br> 1     reads balance: 8,000<br> 2                                reads balance: 8,000<br> 3     8,000 &gt;= 5,000, approved<br> 4                                8,000 &gt;= 5,000, approved<br> 5     writes 3,000, commits<br> 6                                writes 3,000, commits</pre><p>Request B’s write erased Request A’s. One withdrawal is lost from the books, but the money still left.</p><h3>2. Check, then act</h3><p>You check a condition, then act on it, assuming it is still true:</p><pre>public User register(String email) {<br>    if (userRepository.existsByEmail(email)) {<br>        throw new EmailTakenException();<br>    }<br>    return userRepository.save(new User(email));<br>}</pre><p>Two sign-ups with the same email arrive together. Both checks return false. Both saves succeed. You now have two accounts for one email, and your login code that expects exactly one will break.</p><p>The same shape shows up in booking the last seat, redeeming a one-time coupon, and creating “the” cart for a user.</p><h3>A bonus case: state inside a bean</h3><p>Spring beans are singletons by default, so every request shares the same instance:</p><pre>@Service<br>public class StatsService {<br>    private int requestCount = 0;</pre><pre>    public void record() {<br>        requestCount++;<br>    }<br>}</pre><p>requestCount++ looks like one operation. It is three: read the value, add one, write it back. Under load, increments get lost.</p><h3>Why your tests never catch it</h3><p>Race conditions pass code review, pass tests, and work on your laptop. Three reasons:</p><ul><li><strong>Tests send one request at a time.</strong> No overlap, no race.</li><li><strong>The window is tiny locally.</strong> Your database sits on the same machine, so the gap between read and write is microseconds. In production, network latency, slow queries and garbage collection pauses stretch that gap to milliseconds.</li><li><strong>The bug is intermittent.</strong> It shows up as “weird data” weeks later, with no stack trace pointing at the cause.</li></ul><p>To see it, you have to create the overlap yourself. Start several threads, hold them at a gate, then release them together:</p><pre>@Test<br>void onlyOneWithdrawalSucceeds() throws Exception {<br>    int threads = 10;<br>    ExecutorService pool = Executors.newFixedThreadPool(threads);<br>    CountDownLatch gate = new CountDownLatch(1);<br>    AtomicInteger approved = new AtomicInteger();</pre><pre>    List&lt;Future&lt;?&gt;&gt; tasks = new ArrayList&lt;&gt;();<br>    for (int i = 0; i &lt; threads; i++) {<br>        tasks.add(pool.submit(() -&gt; {<br>            gate.await();<br>            try {<br>                accountService.withdraw(accountId, 5_000);<br>                approved.incrementAndGet();<br>            } catch (InsufficientFundsException ignored) {<br>            }<br>            return null;<br>        }));<br>    }</pre><pre>    gate.countDown();<br>    for (Future&lt;?&gt; task : tasks) {<br>        task.get();<br>    }</pre><pre>    assertThat(approved.get()).isEqualTo(1);<br>    assertThat(accountRepository.findById(accountId).orElseThrow().getBalance())<br>        .isEqualTo(3_000);<br>}</pre><p>Run it against the naive withdraw method and you will usually see several approvals while the balance still reads 3,000. That is the lost update, caught in the act.</p><p>Two details matter. Don’t put @Transactional on the test class, or the threads won&#39;t see each other&#39;s data. And run it against a real PostgreSQL instance (Testcontainers works well), because H2 locks differently.</p><h3>How to fix it</h3><p>The goal of every fix is the same: make sure “read, decide, write” cannot be interrupted by another request.</p><h3>1. Let the database do it in one statement</h3><p>The simplest fix is to stop reading the balance into Java at all. Put the check inside the update:</p><pre>@Modifying<br>@Query(&quot;&quot;&quot;<br>    UPDATE Account a<br>    SET a.balance = a.balance - :amount<br>    WHERE a.id = :id AND a.balance &gt;= :amount<br>    &quot;&quot;&quot;)<br>int withdraw(@Param(&quot;id&quot;) Long id, @Param(&quot;amount&quot;) long amount);</pre><pre>@Transactional<br>public void withdraw(Long accountId, long amount) {<br>    if (accountRepository.withdraw(accountId, amount) == 0) {<br>        throw new InsufficientFundsException();<br>    }<br>}</pre><p>The method returns the number of rows changed. Zero means the balance was too low. PostgreSQL locks the row while it updates it, so the second request waits, then re-checks the WHERE clause against the new balance of 3,000 and fails.</p><p>The MongoDB version for MERN projects follows the same idea:</p><pre>const result = await Account.updateOne(<br>  { _id: accountId, balance: { $gte: amount } },<br>  { $inc: { balance: -amount } }<br>);<br>if (result.modifiedCount === 0) throw new InsufficientFundsError();</pre><p>Use this whenever the change fits in one statement: balances, stock counts, counters, likes.</p><h3>2. Optimistic locking with @Version</h3><p>When the logic is too complex for one SQL statement, add a version column:</p><pre>@Entity<br>public class Account {<br>    @Id<br>    private Long id;<br>    private long balance;</pre><pre>    @Version<br>    private Long version;<br>}</pre><p>Hibernate now writes UPDATE account SET balance = ?, version = 4 WHERE id = ? AND version = 3. If another transaction changed the row first, the version no longer matches, zero rows update, and Hibernate throws ObjectOptimisticLockingFailureException.</p><p>You then choose: retry the operation, or return 409 Conflict and let the client reload. This is the right default for things like editing a profile or a product, where two people rarely edit the same record at once.</p><h3>3. Pessimistic locking</h3><p>When many requests fight over the same row, optimistic locking turns into constant retries. Lock the row up front instead:</p><pre>@Lock(LockModeType.PESSIMISTIC_WRITE)<br>@Query(&quot;SELECT a FROM Account a WHERE a.id = :id&quot;)<br>Optional&lt;Account&gt; findByIdForUpdate(@Param(&quot;id&quot;) Long id);</pre><p>This generates SELECT ... FOR UPDATE. Any other transaction asking for that row waits until yours commits. It only works inside a transaction.</p><p>Two costs come with it. Requests queue up, so keep the locked section short and never call an external API while holding the lock. And two transactions can deadlock: A locks account 1 and waits for 2, while B locks 2 and waits for 1. For transfers, always lock accounts in the same order, such as lowest ID first.</p><h3>4. Unique constraints for check-then-act</h3><p>For “this must exist only once”, the database already has the perfect tool:</p><pre>CREATE UNIQUE INDEX uk_users_email ON users (lower(email));</pre><p>Keep the existsByEmail check if you want a friendly error message, but treat it as a courtesy. The constraint is the real guard. When two sign-ups collide, one insert fails with DataIntegrityViolationException, which you turn into a 409.</p><p>The same trick covers one booking per seat, one redemption per coupon, and one cart per user.</p><h3>5. Idempotency keys for double taps and retries</h3><p>The wallet story began with a user tapping twice. The client can send a unique key with each logical action:</p><pre>POST /withdrawals<br>Idempotency-Key: 7f3c9a2e-1b4d-4c8a-9e21-5d6f7a8b9c01</pre><p>The server stores the key in a table with a unique constraint, together with the response. A second request with the same key returns the stored response instead of withdrawing again. This matters most for payments, where a mobile network timeout makes the client retry a request that already succeeded.</p><h3>6. Distributed locks when the database can’t help</h3><p>Sometimes the shared thing isn’t a row. Examples: a scheduled job that must run once even though you deploy three instances, or a call to a payment provider that must happen once per order.</p><p>synchronized won&#39;t help here. It only blocks threads inside one JVM, and your other instances don&#39;t know it exists. You need a lock all instances can see, usually in Redis:</p><pre>SET lock:order:1042 &lt;instance-id&gt; NX PX 30000</pre><p>NX sets the key only if it doesn&#39;t exist. PX 30000 releases it after 30 seconds if your instance crashes. Redisson gives you this as RLock in Java, and ShedLock handles the scheduled-job case with one annotation.</p><p>Be careful: if your work takes longer than the timeout, the lock expires while you are still working and another instance takes it. Keep a database constraint underneath as a backstop.</p><h3>7. State inside the JVM</h3><p>For the counter in the singleton bean, use AtomicInteger, LongAdder, or ConcurrentHashMap.merge(). Better still, don&#39;t keep mutable state in beans at all. Once you scale to two instances, each one has its own counter anyway.</p><h3>Which fix to pick</h3><ul><li><strong>Changing a number</strong> (balance, stock, counter): a conditional UPDATE in one statement.</li><li><strong>Editing a record where conflicts are rare:</strong> @Version optimistic locking, returning 409.</li><li><strong>A busy row with many writers and multi-step logic:</strong> a PESSIMISTIC_WRITE lock.</li><li><strong>Something that must exist only once:</strong> a unique constraint.</li><li><strong>Double taps or network retries:</strong> an idempotency key.</li><li><strong>A shared resource outside the database, across instances:</strong> a Redis lock, with a database constraint as backstop.</li><li><strong>Mutable state inside one JVM:</strong> atomic classes, concurrent collections, or no state at all.</li></ul><p>One rule ties the table together: put the guarantee as close to the data as you can. Your Java code runs on many threads across many instances. The database is the one place they all share, so let it make the final decision.</p><h3>The question to ask in every review</h3><p>Whenever code reads a value, makes a decision, then writes, ask one question: what happens if another request does the same thing between my read and my write?</p><p>If the answer is “nothing bad”, move on. If the answer is “we pay twice” or “we oversell” or “two users get the same email”, the decision belongs to the database, not to an if statement in your service layer.</p><p>Race conditions don’t announce themselves. They wait for real traffic. Write the concurrent test now, before your users write it for you.</p><p>#BackendEngineering #SpringBoot #Java #Concurrency #SoftwareEngineering</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=183c0c61d181" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your REST API Probably Isn’t REST]]></title>
            <link>https://medium.com/@awaprecious3t/your-rest-api-probably-isnt-rest-7143a446ef20?source=rss-9e0881aa60c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7143a446ef20</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Awa precious]]></dc:creator>
            <pubDate>Sat, 03 Oct 2026 14:00:20 GMT</pubDate>
            <atom:updated>2026-10-03T14:00:20.784Z</atom:updated>
            <content:encoded><![CDATA[<p>Your REST API Probably Isn’t REST</p><p>Oct 3, 2026 · @PCodes<br>Day 1 of 100 in The Backend Engineering Series: one topic a day on how real software systems work.</p><p>Almost every backend developer has built a &quot;REST API.&quot; You pick nouns for your URLs, use GET and POST correctly, return JSON, and send sensible status codes. Job done.<br>Here’s the uncomfortable part: by the definition of the person who coined the term, that API is probably not REST. And he has said so publicly, more than once.<br>This isn’t a pedantic argument about words. Understanding what REST actually asks for, and what most of us quietly skip, makes you a sharper API designer. Let’s dig in.<br>Where REST actually came from<br>REST stands for Representational State Transfer. Roy Fielding defined it in 2000, in Chapter 5 of his PhD dissertation at UC Irvine. Fielding was also one of the principal authors of the HTTP specification, so he wasn’t describing a framework. He was describing the architectural style that made the web itself scale.<br>REST is a set of constraints. Each one costs you something and buys you something:<br>1. Client–server. The UI and the data storage evolve separately, so your React app and your Spring Boot service can change independently.<br>2. Stateless. Every request carries everything the server needs to process it. The server can scale horizontally, because any instance can handle any request.<br>3. Cacheable. Responses say whether they can be cached. That cuts latency and load without the client guessing.<br>4. Uniform interface. Every component talks to resources the same way. This is the heart of REST, and we’ll come back to it.<br>5. Layered system. A client can’t tell whether it’s talking to the real server or to a load balancer, cache, or gateway in between.<br>6. Code on demand (optional). The server can send executable code to the client, like JavaScript to a browser.<br>If your API breaks one of the required constraints, Fielding’s position is simple: it may be a fine API, but it isn’t REST.<br>The constraint almost everyone skips<br>The uniform interface is itself made of four smaller constraints:<br>1. Identification of resources. Each resource has an identifier, like /orders/42.<br>2. Manipulation through representations. You don’t touch the order directly. You send and receive representations of it, such as JSON.<br>3. Self-descriptive messages. Each message carries enough information (method, headers, media type) to be understood on its own.<br>4. Hypermedia as the engine of application state (HATEOAS). The server’s responses contain links that tell the client what it can do next.<br>Most APIs handle the first three reasonably well. The fourth is where nearly everyone stops.<br>Think about how you use a website. You don’t memorize the URL of the checkout page. You land on the homepage and follow links and forms the server gives you. If the site moves its checkout page, you never notice. That’s hypermedia driving application state, and it’s why the web can change constantly without breaking billions of browsers.<br>Now think about a typical mobile app or SPA. Its code is full of hardcoded paths like /orders/{id}/payment, plus business rules about when each one is allowed. The client already knows the whole map. By Fielding’s definition, that’s the opposite of REST.<br>&quot;REST APIs must be hypertext-driven&quot;<br>In 2008, Fielding published a blog post with exactly that title. He was frustrated that people were calling any HTTP-based interface a REST API. His core argument: if a client needs out-of-band knowledge, like documentation listing every URL and when to call it, the API isn’t RESTful. A REST client should need only an entry point and an understanding of the media types it receives.<br>A useful way to see where your API sits is the Richardson Maturity Model, popularized by Martin Fowler in 2010:<br>1. Level 0: one endpoint. Everything is a POST to a single URL, like many SOAP and RPC-style APIs.<br>2. Level 1: resources. Separate URLs for separate things, such as /orders and /customers.<br>3. Level 2: HTTP verbs. GET reads, POST creates, PUT and DELETE do what they say, and status codes mean something.<br>4. Level 3: hypermedia controls. Responses include links to related resources and available actions.<br>Most production APIs, including very good ones, live comfortably at Level 2. Fielding’s point is that only Level 3 is REST. Everything below it is better described as an HTTP API.<br>What the difference looks like in code<br>Take a simple order. Here’s a typical Level 2 response:<br>{<br> &quot;id&quot;: 42,<br> &quot;status&quot;: &quot;PENDING&quot;,<br> &quot;total&quot;: 15000<br>}<br>To show a &quot;Pay&quot; button, the client must already know two things: that pending orders can be paid, and that payment lives at /orders/42/payment. Both are hardcoded.<br>Here’s the same order as a Level 3, hypermedia-driven response in the HAL format:<br>{<br> &quot;id&quot;: 42,<br> &quot;status&quot;: &quot;PENDING&quot;,<br> &quot;total&quot;: 15000,<br> &quot;_links&quot;: {<br> &quot;self&quot;: { &quot;href&quot;: &quot;http://localhost:8080/orders/42&quot; },<br> &quot;pay&quot;: { &quot;href&quot;: &quot;http://localhost:8080/orders/42/payment&quot; },<br> &quot;cancel&quot;: { &quot;href&quot;: &quot;http://localhost:8080/orders/42/cancel&quot; }<br> }<br>}<br>Now the server tells the client what’s possible. Once the order is paid, the pay and cancel links disappear. The client’s logic shrinks to one question: is there a pay link?<br>if (order._links.pay) {<br> showPayButton(order._links.pay.href);<br>}<br>In Spring Boot, add the spring-boot-starter-hateoas dependency and build links with WebMvcLinkBuilder:<br>import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.*;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wNSG7tpIPM42Umm9RvBdsA.jpeg" /><figcaption>Example of Richardson level 2 and level 3 APIs</figcaption></figure><p>@RestController<br>@RequestMapping(&quot;/orders&quot;)<br>public class OrderController {</p><p>private final OrderService orderService;</p><p>public OrderController(OrderService orderService) {<br> this.orderService = orderService;<br> }</p><p>@GetMapping(&quot;/{id}&quot;)<br> public EntityModel&lt;OrderDto&gt; getOrder(@PathVariable Long id) {<br> OrderDto order = orderService.findById(id);</p><p>EntityModel&lt;OrderDto&gt; model = EntityModel.of(order,<br> linkTo(methodOn(OrderController.class).getOrder(id)).withSelfRel());</p><p>// Only advertise actions that are valid right now<br> if (order.status() == OrderStatus.PENDING) {<br> model.add(linkTo(methodOn(OrderController.class).pay(id)).withRel(&quot;pay&quot;));<br> model.add(linkTo(methodOn(OrderController.class).cancel(id)).withRel(&quot;cancel&quot;));<br> }<br> return model;<br> }</p><p>@PostMapping(&quot;/{id}/payment&quot;)<br> public ResponseEntity&lt;Void&gt; pay(@PathVariable Long id) {<br> orderService.pay(id);<br> return ResponseEntity.noContent().build();<br> }</p><p>@PostMapping(&quot;/{id}/cancel&quot;)<br> public ResponseEntity&lt;Void&gt; cancel(@PathVariable Long id) {<br> orderService.cancel(id);<br> return ResponseEntity.noContent().build();<br> }<br>}<br>The business rule &quot;only pending orders can be paid&quot; now lives in one place: the server. If it changes, every client follows automatically.<br>So why does almost nobody do this?<br>Because for most teams, the tradeoff isn&#39;t worth it. That&#39;s a legitimate engineering decision, not laziness.<br>• You control both ends. When the same team builds the API and its only frontend, and deploys them together, hardcoded paths cost very little.<br>• Links aren&#39;t enough on their own. A link tells a client where to go, not what the action means. A program still needs to understand pay in advance, so it isn&#39;t as self-discovering as a human with a browser.<br>• Tooling grew up around Level 2. OpenAPI, code generators, and most client libraries assume a fixed set of documented endpoints.<br>• Payloads get bigger. Links on every resource add bytes and complexity, especially in large collections.<br>There&#39;s also a sharp counterargument worth knowing. Carson Gross, creator of htmx, argues that hypermedia works best when a human is on the other end. The browser reading HTML is the one hugely successful REST client, because people interpret links and forms on the fly. JSON APIs consumed by code, he argues, are a poor fit for HATEOAS by nature.<br>Where hypermedia does pay off: public APIs with many independent clients, long-lived systems where workflows change often, and anywhere you want business rules to live only on the server.<br>The takeaway<br>You don&#39;t need to rewrite your API. You do need to be honest about what it is.<br>If your API uses resources, verbs, and status codes but no hypermedia, call it what it is: a well-designed HTTP API. That&#39;s a perfectly good thing to build. What matters is knowing which of REST&#39;s constraints you&#39;re skipping, and being able to explain why.<br>That&#39;s the difference between following a convention and making an architectural decision.<br>Up next, Day 2: I&#39;ll build an HTTP server from raw TCP sockets, with no frameworks, to show that HTTP is just text over a wire.<br>Have you ever worked with a truly hypermedia-driven API? Did it pay off? I&#39;d love to hear about it in the comments.<br>Further reading<br>• Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures, Chapter 5 (2000)<br>• Roy Fielding, REST APIs must be hypertext-driven (2008)<br>• Martin Fowler, Richardson Maturity Model (2010)<br>• htmx essays, HATEOAS<br>• Carson Gross and co-authors, Hypermedia Systems (2023)<br>• Spring HATEOAS reference documentation</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7143a446ef20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The CAP Theorem: The Unavoidable Trade-off in Distributed Systems]]></title>
            <link>https://medium.com/@awaprecious3t/the-cap-theorem-the-unavoidable-trade-off-in-distributed-systems-3750b582ab6c?source=rss-9e0881aa60c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3750b582ab6c</guid>
            <dc:creator><![CDATA[Awa precious]]></dc:creator>
            <pubDate>Mon, 12 Jan 2026 19:49:06 GMT</pubDate>
            <atom:updated>2026-01-12T19:51:27.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWXRPVTDJ-YS_oAIUFbWgw.png" /></figure><p>Distributed systems power almost everything we use today — from banking applications and cloud platforms to social media and streaming services. Yet, beneath all this complexity lies a simple but unforgiving principle that every distributed system must obey: <strong>the CAP Theorem</strong>.</p><p>The CAP Theorem is not a guideline or a best practice. It is a <strong>fundamental constraint</strong>. No matter how sophisticated your architecture is, CAP applies.</p><h3>What Is the CAP Theorem?</h3><p>The CAP Theorem states that a distributed system can provide <strong>at most two</strong> of the following three guarantees at the same time:</p><ul><li><strong>Consistency(C)</strong><br> Every read receives the most recent write or an error. All nodes see the same data at the same time.</li><li><strong>Availability (A)</strong><br> Every request receives a response, even if that response may not contain the latest data.</li><li><strong>Partition Tolerance (P)</strong><br> The system continues to operate despite network failures, such as dropped packets, latency spikes, or broken links between nodes.</li></ul><p>In real-world distributed systems, <strong>network partitions are unavoidable</strong>. Hardware fails, packets are lost, and networks become unreliable. As a result, <strong>partition tolerance is not optional</strong> — it is a requirement.</p><p>This leaves system designers with a hard choice:<br> <strong>Consistency or Availability?</strong></p><h3>Why Partition Tolerance Is Non-Negotiable</h3><p>In theory, one might imagine a system that avoids partitions entirely. In practice, this is impossible at scale.</p><p>Distributed systems operate across:</p><ul><li>Multiple machines</li><li>Different data centers</li><li>Geographic regions</li><li>Unreliable networks</li></ul><p>Given this reality, partitions will happen. The real design decision is <strong>how the system behaves when they do</strong>.</p><h3>Consistency-First Systems: Banking and Financial Applications</h3><p>For financial systems, <strong>consistency is non-negotiable</strong>.</p><p>Imagine a scenario where:</p><ul><li>Money is debited from one account</li><li>But not credited to another</li><li>Due to network delays or partial failures</li></ul><p>This is not just a bug — it’s a disaster🤯.</p><p>Banking systems therefore prioritize <strong>strong consistency</strong>, even if it means temporarily rejecting requests or becoming unavailable during a network partition. Correctness and data integrity always take precedence over uptime.</p><p>In CAP terms, these systems choose:</p><ul><li><strong>Consistency(C)</strong></li><li><strong>Partition Tolerance (P)</strong></li><li>And sacrifice <strong>Availability (A)</strong> when necessary</li></ul><h3>Availability-First Systems: Social Media and Content Platforms</h3><p>Social media platforms like <strong>Instagram, TikTok, and Twitter (X)</strong> operate under very different requirements.</p><p>Users expect:</p><ul><li>The app to open instantly</li><li>Feeds to load continuously</li><li>Interactions to feel smooth and responsive</li></ul><p>If a profile picture update or a post takes a few seconds — or even minutes — to propagate across all servers, that’s acceptable. What’s unacceptable is the app failing to respond.</p><p>These systems favor <strong>high availability</strong> and rely on <strong>eventual consistency</strong>:</p><ul><li>Updates may not be immediately visible everywhere</li><li>But over time, all replicas converge to the same state</li></ul><p>In CAP terms, these platforms choose:</p><ul><li><strong>Availability (A)</strong></li><li><strong>Partition Tolerance (P)</strong></li><li>And relax <strong>Consistency(C)</strong></li></ul><h3>Common Misconceptions About CAP</h3><p>A frequent misunderstanding is believing that CAP is about choosing two properties forever. In reality:</p><ul><li>CAP trade-offs apply <strong>during network partitions</strong></li><li>Outside of partitions, systems can often provide both consistency and availability</li><li>Modern systems may shift behavior dynamically based on context</li></ul><p>CAP doesn’t limit innovation — it forces <strong>intentional design</strong>.</p><h3>CAP Is About Trade-offs, Not Preferences</h3><p>The most important lesson of the CAP Theorem is this:</p><blockquote><em>CAP is not about what you want.<br> It’s about what you are willing to give up when failure occurs.</em></blockquote><p>Every distributed system makes a choice — explicitly or implicitly. The best systems are designed with a deep understanding of these trade-offs and align them with business and user needs.</p><h3>Final Thoughts</h3><p>The CAP Theorem remains as relevant today as it was when first introduced. Cloud-native architectures, microservices, and globally distributed databases have not invalidated it — they have made it more important.</p><p>Understanding CAP is not optional for software engineers working with distributed systems. It is foundational knowledge that shapes how reliable, scalable, and trustworthy systems are built.</p><p>Design wisely — because CAP will decide for you if you don’t.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3750b582ab6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>