🚨 Duplicate requests can break your system Real scenario: Payment API was called twice due to network retry 💥 Result: Double payment 😬 ✅ Solution: Implemented idempotency - Used unique request ID - Stored request state in DB 💡 Takeaway: APIs should be safe for retries. Especially for payments, orders, critical operations. #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #Microservices #JPA #RESTAPI #DeveloperLife #CareerGrowth
Preventing Double Payments with Idempotency in APIs
More Relevant Posts
-
Topic: API Idempotency Keys Retries are common in distributed systems. Duplicate side effects shouldn’t be. When clients retry requests (timeouts, network issues), you can end up with: • Duplicate payments • Multiple order creations • Inconsistent state Idempotency keys solve this. How it works: • Client sends a unique key with the request • Server stores the result for that key • Repeated requests return the same result Benefits: • Safe retries • Consistent outcomes • Better reliability Common use cases: • Payments • Order processing • External integrations Because in distributed systems, retries are normal— duplicate side effects are not. Do you use idempotency keys in your APIs? #API #Microservices #SystemDesign #Java #BackendDevelopment
To view or add a comment, sign in
-
🚀 Built a Secure Payment API using Spring Boot & HmacSHA256 Authentication Today I implemented a mini project to understand how secure communication works between external systems and backend services. In this project, I designed a Spring Boot API where incoming payment requests are verified using HmacSHA256 signatures before reaching the controller layer. 🔹 Implemented a custom HmacFilter using Spring Security 🔹 Added ExceptionHandlerFilter to manage filter-level errors 🔹 Verified request integrity using HmacSHA256 signature validation 🔹 Explored how Spring Security Filter Chain works internally 🔹 Debugged request flow using breakpoints to understand filter execution Request Flow: Client → ExceptionHandlerFilter → HmacFilter → PaymentController This hands-on implementation helped me deeply understand: ✔ API authentication mechanisms ✔ Spring Security filter architecture ✔ Handling exceptions outside controllers Excited to continue exploring backend security patterns and building scalable microservices using Java & Spring Boot. #Java #SpringBoot #SpringSecurity #BackendDevelopment #JavaDeveloper #LearningInPublic
To view or add a comment, sign in
-
-
10,000 DB queries. Per. API. Call. 💀 We had no idea until latency hit 5 seconds and started laughing at us. Upon checking... We had a loop that called save() on every entity individually. Looked harmless. worked fine at low traffic. Then production came in. 10k entities → 10k DB hits → 5 second response time. Classic N+1 Db query. hiding in plain sight. Fix was almost straightforward — Instead of save() inside the loop ,use saveAll() outside it. One or multiple batch insert. done. Latency dropped. DB stopped crying. 😅 This would've slipped into prod unnoticed at low traffic. Scale is what revealed it. Before making any API public, always ask: "what does this look like at 10x traffic?" ⚡ What's the sneakiest N+1 you've caught in prod? 👇 #Java #SpringBoot #BackendDevelopment #SystemDesign #SoftwareEngineering
To view or add a comment, sign in
-
-
🚨 Ever wondered how payment gateways prevent double charges when users refresh the page or retry a payment? ✅ Solution: Idempotency Keys An idempotency key is a unique identifier attached to a request so the server can recognize: “This operation was already processed earlier.” 💡 Real Question: Who should generate the idempotency key? Client side or backend? 👉 Best practice: Client should generate it Why? Because the client is the one retrying the request. If the backend generates a new key for every retry, it cannot identify duplicates. Typical flow: 1️⃣ Client generates a UUID before sending payment request 2️⃣ Backend stores: idempotency key request payload hash response/result 3️⃣ If user refreshes or retries: same key is sent again backend checks DB/cache returns existing result instead of processing again In distributed systems, idempotency is not just an optimization — it’s a reliability guarantee. But how do the client side maintains uniqueness when the UI is re-rendered and the same user tries again ? Comment your answer below. #Backend #SystemDesign #Microservices #Payments #Java #SpringBoot #DistributedSystems #SoftwareEngineering
To view or add a comment, sign in
-
Deep Dive into Error Handling & Request Validation in Payment Systems I recently worked on designing a robust error handling and validation mechanism for a payment integration system (Stripe-based), and documented the complete approach in this PDF: Here’s what I explored and implemented: 🔹 Structured Error Handling in Spring Boot Clear separation of 2xx (success), 4xx (client), and 5xx (server) responses Custom exception (StripeProviderException) with HTTP status, error code, and message Global exception handling using @RestControllerAdvice for clean and consistent responses 🔹 Standardized Error Codes 10xxx → Validation layer 20xxx → Processing layer 30xxx → External provider (Stripe) Helps quickly identify where the failure occurred in a distributed system 🔹 Validation First Approach Dedicated ValidationService to validate requests before business logic Fail-fast mechanism using custom exceptions 🔹 Handling External API (Stripe) Scenarios ✅ Success responses (2xx) → parsed and mapped ⚠️ Client/Server errors (4xx/5xx) → structured error handling ❌ No response (timeouts, network issues) → handled using retry-ready exception strategy 🔹 Dynamic Error Message Construction Handling inconsistent error formats from Stripe Creating meaningful messages using: type | message | code | param 🔹 Clean Service Design Separation of concerns between: HTTP layer Validation layer Business logic Exception handling This project helped me understand how real-world systems handle failures gracefully, especially in payment integrations where reliability is critical. GitHub Repository: https://lnkd.in/dBcjJwEF Always open to feedback and discussions! 🙌 #Java #Spring #SpringBoot #BackendDevelopment #ErrorHandling #SystemDesign #RestAPI #APIDesign #FullStackDeveloper #PaymentIntegration
To view or add a comment, sign in
-
One of the most abused annotations in Spring is @Transactional. People treat it like a “wrap everything and forget” switch. I’ve seen methods like this: 👉 save to DB 👉 call external payment API 👉 send email 👉 call another microservice 👉 update DB again All inside ONE transaction. Looks clean. Feels safe. It’s not. Because the moment you mix DB + external calls inside a transaction, things start getting messy: ⚠️ external APIs are slow ⚠️ transactions stay open longer (locks, performance issues) ⚠️ if API fails → DB rolls back, but external system doesn’t ⚠️ debugging becomes painful Now you have inconsistent systems and no clear recovery path. The better way? Keep @Transactional boring. ✔️ only DB operations inside ✔️ keep it short ✔️ do external calls before or after ✔️ think about failure scenarios explicitly @Transaction is not a safety net. It’s a boundary. Use it wrong → hidden bugs Use it right → stable systems Learned this the hard way 🙂 #Java #SpringBoot #BackendEngineering #SystemDesign #Microservices #CodeQuality
To view or add a comment, sign in
-
-
Day 3 of Building an Offline UPI Payment System with Spring Boot Today I implemented idempotency in the payment flow using a unique requestId, while also studying the importance of concurrency handling in payment systems. What was added: • Duplicate payment requests are detected and blocked • Prevents double debit during retries or network interruptions • Proper 409 CONFLICT response handling • Custom exception flow for cleaner API behavior • Initial understanding of how concurrent duplicate requests can impact transactions Why this matters: In payment systems, retries and simultaneous requests are common. Without idempotency and concurrency safeguards, the same transaction can be processed multiple times. Current implementation works, but there is room to improve: Areas of improvement: • Return the original transaction response instead of only throwing duplicate error • Strengthen concurrent request handling with DB constraints / locking strategies • Add request payload validation for reused requestId • Introduce expiry/cleanup strategy for old idempotency keys • Improve observability with logs and audit trails Next step: I’ll be upgrading this into a more production-ready payment flow by improving concurrency safety and returning previous transaction state on retries. Built with: -Spring Boot -Spring Data JPA -H2 -REST APIs -Java Reliable backend systems are built by handling retries, race conditions, and edge cases not just successful requests. #Java #SpringBoot #BackendEngineering #Concurrency #Payments #SystemDesign #RESTAPI #SoftwareEngineering #LearningInPublic #Fintech
To view or add a comment, sign in
-
Most backend bugs don't come from bad logic — they come from a bad middleware order. Here's the structure of strong middleware (save this): What is middleware? It sits between the client request and your handler — transforming, validating, and enriching data as it flows through. The 7 layers — in order of execution: 🔌 Transport — parse body, decompress, terminate TLS 🛡️ Security — rate limiting, CORS, header sanitization 🔐 Authentication — verify identity (JWT, API key, session) ✅ Authorization — roles, ACLs, policy checks 📋 Validation — reject bad request shape before expensive work 🧩 Context Enrichment — attach user, tenant, feature flags 📊 Error & Logging — normalize errors, trace request ID + duration The golden rule of middleware: Security and validation always run BEFORE business logic. Every time. The Onion Pattern — each middleware wraps the next: What makes middleware STRONG: → Single responsibility — one job per unit → Fail fast — reject bad requests early → Stateless — pass state through context, not memory → Composable — stackable in explicit, deliberate order → Observable — consistent request IDs across all logs → Tested in isolation — each unit independently testable Strong middleware = predictable systems. Weak middleware = bugs that only appear in production. 😅 ♻️ Repost if this helped a teammate today. 💬 What's the worst middleware bug you've debugged? Drop it below 👇 #BackendEngineering #WebDevelopment #SoftwareEngineering #NodeJS #SystemDesign #Programming #CleanCode #100DaysOfCode2
To view or add a comment, sign in
-
-
Recently I improved my reporting service by applying Strategy Pattern. Earlier, I was using multiple APIs for different report types. Each API had its own logic, and it was getting difficult to manage and scale. Now I moved to a single generic API. Based on the request, I select the required strategy and generate the report. What I learned: - Reduced multiple APIs into one clean generic API - Removed lots of if-else conditions - Code is now more flexible and easy to extend - Adding new report type is simple, just add new strategy - Better maintainability and cleaner structure This change made the system more scalable and easy to handle. Small design improvement, but big impact. #Java #StrategyPattern #BackendDevelopment #CleanCode #Microservices
To view or add a comment, sign in
-
🤫This extensive guide covers everything from the basics of Spring Boot microservices to advanced production-grade patterns, all within the context of a banking application. It includes: •Detailed explanations for each topic. •Practical Spring Boot code examples for every concept. •High-quality architectural diagrams to illustrate complex flows. •Integration with PostgreSQL and Apache Kafka for a realistic banking scenario. •Deep dives into concurrent transaction handling, security, resilience, and observability. #java #springboot #banking #microservice
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development