<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Piyush Kumar Singh</title>
    <description>The latest articles on DEV Community by Piyush Kumar Singh (@piyushsingh_dev).</description>
    <link>https://dev.to/piyushsingh_dev</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3909333%2Fe0081e0c-5341-42fe-b711-92dafd3e0fdb.jpg</url>
      <title>DEV Community: Piyush Kumar Singh</title>
      <link>https://dev.to/piyushsingh_dev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/piyushsingh_dev"/>
    <language>en</language>
    <item>
      <title>I Cleared the GitHub Copilot GH-300 Certification: Syllabus, Key Topics &amp; My Study Notes</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Sun, 08 Nov 2026 04:21:58 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/i-cleared-the-github-copilot-gh-300-certification-syllabus-key-topics-my-study-notes-ikl</link>
      <guid>https://dev.to/piyushsingh_dev/i-cleared-the-github-copilot-gh-300-certification-syllabus-key-topics-my-study-notes-ikl</guid>
      <description>&lt;p&gt;I’m excited to share that I’ve successfully cleared the Microsoft GitHub Copilot GH-300 Certification!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fn8lk3h6671ge7v02b99g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fn8lk3h6671ge7v02b99g.png" alt=" " width="800" height="533"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As a software engineer, I wanted to understand more than just how GitHub Copilot generates code. I wanted to explore how it works, how developers can use it effectively, its limitations, and how AI-assisted development fits into modern software engineering.&lt;/p&gt;

&lt;p&gt;During my preparation, I organized my learning into 20 units and converted the material into structured notes with explanations, comparison tables, practical examples, and practice questions.&lt;/p&gt;

&lt;p&gt;In this article, I’m sharing the major topics I covered and the study material I created to help other developers prepare.&lt;/p&gt;

&lt;h2&gt;
  
  
  1. What does the GH-300 certification cover?
&lt;/h2&gt;

&lt;p&gt;The GitHub Copilot certification focuses on understanding AI-assisted software development and using GitHub Copilot effectively.&lt;/p&gt;

&lt;p&gt;My preparation covered these important areas:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Responsible AI:&lt;/strong&gt; AI risks and Microsoft’s six Responsible AI principles, fairness, transparency, and human oversight.&lt;br&gt;
GitHub Copilot fundamentals: Features, plans, capabilities, and interaction modes.&lt;br&gt;
&lt;strong&gt;Prompt engineering:&lt;/strong&gt; Writing effective prompts, providing context, and improving AI-generated responses.&lt;br&gt;
&lt;strong&gt;LLMs and AI concepts:&lt;/strong&gt; How Copilot processes prompts, context windows, data handling, fine-tuning, and LoRA.&lt;br&gt;
Developer workflows: Using Copilot Chat, Copilot on GitHub.com, and AI assistance across development tasks.&lt;br&gt;
Copilot customization: Plans, policies, management, and repository-level instructions.&lt;br&gt;
&lt;strong&gt;Testing and productivity:&lt;/strong&gt; Generating unit tests, developer use cases, productivity measurement, and Copilot limitations.&lt;br&gt;
Agent Mode: Understanding autonomous, multi-step development workflows.&lt;br&gt;
Security: Risks, limitations, and security considerations when using Copilot in the cloud.&lt;br&gt;
&lt;strong&gt;Premium Request Units (PRUs):&lt;/strong&gt; Understanding premium-level tasks and usage considerations.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Important GitHub Copilot concepts to understand
&lt;/h2&gt;

&lt;p&gt;Some concepts deserve extra attention because they help distinguish similar features and workflows.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Copilot interaction modes&lt;/strong&gt;&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fscex6w1wud5wxo586riz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fscex6w1wud5wxo586riz.png" alt=" " width="800" height="203"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Remember: Agent Mode can analyze project files, modify code, execute terminal commands, run tests, review results, and iterate. Developers still need to review and validate its output.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prompt engineering&lt;/strong&gt;&lt;br&gt;
A good prompt should clearly communicate the task, context, and expected outcome.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;p&gt;Vague prompt:&lt;br&gt;
// Create an API endpoint&lt;/p&gt;

&lt;p&gt;More specific prompt:&lt;br&gt;
// Create an API endpoint using the React framework that accepts a JSON payload in a POST request.&lt;/p&gt;

&lt;p&gt;The more clearly you describe your requirements, the better Copilot can understand the intended task.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Responsible AI and security&lt;/strong&gt;&lt;br&gt;
Never accept AI-generated code blindly. Developers must review generated output, consider privacy and security risks, test changes, and follow organizational policies.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Premium Request Units&lt;/strong&gt;&lt;br&gt;
Understand the distinction between routine lightweight tasks and more advanced, context-rich tasks, such as reviewing large pull requests using repository-specific instructions.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. How I organized my preparation notes
&lt;/h2&gt;

&lt;p&gt;I created a structured study guide covering 20 learning units. Each unit is designed to help with:&lt;/p&gt;

&lt;p&gt;Understanding important concepts and technical terminology.&lt;br&gt;
Reviewing comparison tables and practical examples.&lt;br&gt;
Remembering important distinctions and exam-focused points.&lt;br&gt;
Practicing multiple-choice questions with answers and explanations.&lt;br&gt;
Identifying common exam traps.&lt;br&gt;
Revising key takeaways quickly.&lt;br&gt;
Rather than keeping everything in scattered documents, I consolidated the learning material into one study guide.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. My advice to developers preparing for GH-300
&lt;/h2&gt;

&lt;p&gt;A few suggestions from my preparation experience:&lt;/p&gt;

&lt;p&gt;Understand the concepts instead of relying only on memorization.&lt;br&gt;
Learn the differences between Copilot’s interaction modes.&lt;br&gt;
Pay attention to Agent Mode and prompt engineering.&lt;br&gt;
Understand Responsible AI, security, and data-handling considerations.&lt;br&gt;
Practice scenario-based questions and focus on why an answer is correct.&lt;br&gt;
Revise important terminology, limitations, and feature distinctions.&lt;br&gt;
Most importantly, don’t treat GitHub Copilot as just an autocomplete tool. Understand how it supports the broader software development lifecycle.&lt;/p&gt;

&lt;h2&gt;
  
  
  5. Get my GH-300 certification study notes.
&lt;/h2&gt;

&lt;p&gt;I’ve made my preparation notes available for developers who want a structured resource for their own GH-300 preparation.&lt;/p&gt;

&lt;p&gt;What’s included?&lt;/p&gt;

&lt;p&gt;20 structured learning units.&lt;br&gt;
Easy-to-understand concept explanations.&lt;br&gt;
Comparison tables and practical examples.&lt;br&gt;
Practice MCQs with answers and explanations.&lt;br&gt;
Exam traps and quick revision notes.&lt;br&gt;
&lt;a href="https://topmate.io/code_with_clarity/2389572?utm_source=medium&amp;amp;utm_medium=article&amp;amp;utm_campaign=gh300_study_guide" rel="noopener noreferrer"&gt;Get the GitHub Copilot GH-300 Study Guide.&lt;/a&gt; The guide is independently prepared from the learning material I used during my preparation. It is not an official Microsoft or GitHub publication.&lt;/p&gt;

&lt;h2&gt;
  
  
  Final thoughts
&lt;/h2&gt;

&lt;p&gt;Clearing the GH-300 certification was a valuable learning experience. More importantly, preparing for it helped me develop a better understanding of AI-assisted software development and how developers can work effectively with tools like GitHub Copilot.&lt;/p&gt;

&lt;p&gt;I hope sharing my preparation notes helps other developers make their learning journey more organized.&lt;/p&gt;

&lt;p&gt;Happy learning, and all the best for your GH-300 certification!&lt;/p&gt;

&lt;p&gt;If you found this useful, follow me on Medium for more practical content on backend engineering, AI tools, system design, and developer learning.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Claude Certified Developer Exam: Passing Score, Syllabus, and My 5-Step Study Plan</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Thu, 05 Nov 2026 15:57:51 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/claude-certified-developer-exam-passing-score-syllabus-and-my-5-step-study-plan-1j90</link>
      <guid>https://dev.to/piyushsingh_dev/claude-certified-developer-exam-passing-score-syllabus-and-my-5-step-study-plan-1j90</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdddoqig0v8dlopowqjtc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fdddoqig0v8dlopowqjtc.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;br&gt;
I passed the Claude Certified Developer—Foundations exam with 896 out of 1000, and I wrote down how I got there so you don’t have to piece it together from five different pages. Friend’s link&lt;/p&gt;

&lt;p&gt;I’m not affiliated with Anthropic, and I won’t share any exam questions. I checked the exam details below against the official certification page and FAQ.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is the exam about?
&lt;/h2&gt;

&lt;p&gt;The exam is for engineers who build with the Claude API, Claude Code, and the Model Context Protocol (MCP), from a first integration all the way to agents running in production. Writing good prompts is only a small part of it. Most of the questions describe a situation and ask which approach fits and why.&lt;/p&gt;

&lt;p&gt;Important eligibility note: As of 26 October 2026, Anthropic’s certification program is restricted to people at Claude Partner Network organizations. Registration requires a recognized company-domain email address. Check the current eligibility rules before you buy the exam. Here are the practical details from the official FAQ:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Format:&lt;/strong&gt; The FAQ lists multiple-choice and scenario-based multiple-response questions. My attempt had 53 questions, all multiple-choice&lt;br&gt;
&lt;strong&gt;Time:&lt;/strong&gt; 120 minutes to answer. Plan for about 135 minutes in total, because check-in and instructions take time.&lt;br&gt;
Where: online with OnVUE proctoring or at a Pearson test center. It’s closed book.&lt;br&gt;
Cost: $125.&lt;br&gt;
&lt;strong&gt;Who can take it:&lt;/strong&gt; you need to be 18 or older and carry a government-issued ID. Read the eligibility note above and the “who can take an exam” page before you plan anything else.&lt;br&gt;
Validity: 12 months. Renewal is a free, non-proctored assessment.&lt;br&gt;
The official source is the Anthropic certification page, and the certification FAQ has the rules.&lt;/p&gt;

&lt;h2&gt;
  
  
  Syllabus and topics, at a high level
&lt;/h2&gt;

&lt;p&gt;For the official domains and how much each one counts, open the exam guide PDF linked from the certifications page. This is the list my own notes were built around:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Tokens, context windows, sampling, and model selection&lt;/strong&gt;&lt;br&gt;
Prompt engineering, XML tags, and structured outputs&lt;br&gt;
SDKs, REST APIs, streaming, and asynchronous processing&lt;br&gt;
Tool schemas and the tool-use lifecycle&lt;br&gt;
Agents, workflows, orchestration, and human approval&lt;br&gt;
Persistent memory, context compaction, and skills&lt;br&gt;
Images, PDFs, and batch processing&lt;br&gt;
Security, evaluation, testing, and debugging&lt;br&gt;
Trade-offs show up everywhere in these topics. Four kept coming back in my notes:&lt;/p&gt;

&lt;p&gt;Workflow or agent? When the steps never change, a plain workflow is usually the better design. An agent makes sense when the next step depends on what just happened.&lt;br&gt;
&lt;strong&gt;Sync, streaming, or batch?&lt;/strong&gt; Ask whether a user is waiting, whether partial output helps, and whether the work can finish later.&lt;br&gt;
Long conversations. Each turn makes you decide what to keep, summarize, store, or drop, and every choice costs something.&lt;br&gt;
Tool use. The model requests a tool call, but your application runs it and returns the result. Clear tool descriptions, error handling, stop conditions, and human approval for risky actions all matter.&lt;br&gt;
Passing marks&lt;br&gt;
You get a scaled score from 100 to 1,000, and the minimum passing score is 720. "Scaled" means it isn’t the percentage of questions you got right. The FAQ doesn’t list a question count, but my exam had 53 multiple-choice questions.&lt;/p&gt;

&lt;p&gt;I scored 896, which is 176 points over the line. I wouldn’t aim for 720 and hope, though. A failed attempt means a wait: 14 days after the first, 30 after the second, 90 after the third, and no more than four attempts in any 12 months. Each retake costs the full fee.&lt;/p&gt;

&lt;p&gt;My preparation strategy: one topic, one set of notes, then questions&lt;br&gt;
The best thing I did was stop treating the syllabus as one huge subject. I split it into sections and added each one to the same master document, so the notes grew as I understood more. Every section I added followed the same layout:&lt;/p&gt;

&lt;p&gt;Core concepts and the technical distinctions between ideas that look alike&lt;br&gt;
Memory hooks for the things that are easy to forget&lt;br&gt;
Common mistakes and exam traps&lt;br&gt;
Active-recall questions&lt;br&gt;
Scenario-based multiple-choice questions, each with an explanation of why the answer is right&lt;br&gt;
A quick revision card for the last few days before the exam&lt;br&gt;
You can copy that layout today and use it for any syllabus. I also answered five questions for every section:&lt;/p&gt;

&lt;p&gt;What does this mean?&lt;br&gt;
Why does it matter?&lt;br&gt;
When would I use it?&lt;br&gt;
What can go wrong?&lt;br&gt;
How would I spot the right approach in a real scenario?&lt;br&gt;
The last one changed how I revised. Memorizing a definition got me nowhere, so I had to picture the concept running inside a real application.&lt;/p&gt;

&lt;p&gt;Every section also got its own practice questions. For active recall, I explained the concept without looking at my notes. For scenarios, I read a situation, picked an approach, and wrote down why the other options were weaker.&lt;/p&gt;

&lt;p&gt;Want to study with my notes?&lt;br&gt;
Get my Claude Developer Foundations Study Notes →&lt;/p&gt;

&lt;p&gt;These are independently prepared personal study notes, not official Anthropic material. They are intended to support your learning and revision; they do not contain a promise of exam success or guarantee a passing score.&lt;/p&gt;

&lt;p&gt;Keep an error log&lt;br&gt;
If I started again, I’d keep an error log from day one. Whenever you get a practice question wrong or get it right for the wrong reason, write down three things:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Concept: what the question was really testing&lt;/strong&gt;&lt;br&gt;
My wrong assumption: what I believed at the time&lt;br&gt;
Rule to remember: the decision rule that would have given me the right answer.&lt;br&gt;
Reading that log is a better use of an evening than rereading a section you already know.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The 5-step study plan I would follow again&lt;/strong&gt;&lt;br&gt;
This is the short version of everything above, in the order I’d do it again.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Complete the official prep course. Start with the official developer prep course. It’s the closest thing to the real scope of the exam, so don’t swap it for a video or a cheat sheet.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Take some mock tests. Practice exams show you the gaps your notes hide. Look for questions written specifically for the Developer—Foundations exam. Use every mock question to find a weak spot, and don’t expect the real exam to look the same.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Use Claude to practice whatever you learn. Take a topic you just studied and ask Claude to quiz you on it. Ask for scenario questions, answer them yourself first, and only then read the explanation. Check anything version-specific against the current documentation, because practice questions from any AI are study aids and not official exam questions.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Register for the exam. Once the course, the mock tests, and your notes feel solid, register here. It costs $125, so check eligibility first, then choose online proctoring or a test center.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Be calm. By now you’ve done the course, the mock tests, and the notes. The exam is closed book, and you have 120 minutes. Get your ID ready, and if you’re testing online, check your setup the day before. Read each scenario all the way through before you look at the options.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>career</category>
      <category>claude</category>
      <category>learning</category>
      <category>llm</category>
    </item>
    <item>
      <title>Your JWT lasts 7 days. Here’s What Happens When Someone Steals It.</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Sat, 17 Oct 2026 17:48:05 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/your-jwt-lasts-7-days-heres-what-happens-when-someone-steals-it-1blp</link>
      <guid>https://dev.to/piyushsingh_dev/your-jwt-lasts-7-days-heres-what-happens-when-someone-steals-it-1blp</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F77jk0ub27ujnwekm7vkw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F77jk0ub27ujnwekm7vkw.png" alt=" " width="800" height="450"&gt;&lt;/a&gt;&lt;br&gt;
This is the next piece in my Spring Security series, after how JWT authentication works, how OAuth2 login works, and how method-level security works. Those were about how a request gets in. This one is about how a user stays logged in without leaving the door open.&lt;/p&gt;

&lt;p&gt;Imagine a user logs into your application. Your Spring Boot API issues a JWT valid for seven days. Three days later, someone steals that token.&lt;/p&gt;

&lt;p&gt;The user changes their password immediately. Problem solved, right?&lt;/p&gt;

&lt;p&gt;Not necessarily. Unless your application has a mechanism to invalidate that token, the stolen JWT can remain valid until it expires. That’s one of the biggest trade-offs of stateless JWT authentication. And it’s why refresh token rotation matters.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why you can’t just “delete” a JWT
&lt;/h2&gt;

&lt;p&gt;A JWT is stateless by design. Your server checks the signature and the expiry date, and that’s it. It never looks anything up in a database, which is exactly why JWTs are fast and easy to scale.&lt;/p&gt;

&lt;p&gt;It’s also why they’re hard to take back. There’s no record on your side to delete. The token is valid because of what’s written inside it, and nothing you do later can change what’s written inside it. Changing the password doesn’t help. Logging out on the real user’s device doesn’t help. The token just sits there, valid, until the clock runs out.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why short-lived access tokens aren’t enough&lt;/strong&gt;&lt;br&gt;
A JWT is typically validated using its signature and expiration time. If your API doesn’t check a revocation mechanism, changing a password or logging out doesn’t automatically invalidate an already-issued token.&lt;/p&gt;

&lt;p&gt;One solution is to shorten the access token’s lifetime. But forcing users to log in every 10–15 minutes isn’t a great experience.&lt;/p&gt;

&lt;p&gt;Instead, most applications separate authentication into two tokens:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Access token:&lt;/em&gt;&lt;/strong&gt; Short-lived, often 5–15 minutes, and sent with API requests.&lt;br&gt;
&lt;strong&gt;&lt;em&gt;Refresh token:&lt;/em&gt;&lt;/strong&gt; Longer-lived and used to obtain a new access token when necessary.&lt;br&gt;
This limits the usefulness of a stolen access token. But what if the attacker steals the refresh token? They could keep obtaining new access tokens until the refresh token expires or is revoked. That’s where rotation comes in.&lt;/p&gt;

&lt;h2&gt;
  
  
  How refresh token rotation works
&lt;/h2&gt;

&lt;p&gt;The rule is simple: every successful refresh replaces the old refresh token with a new one. Imagine this sequence:&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fekths712mk40qhxc23lf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fekths712mk40qhxc23lf.png" alt=" " width="800" height="300"&gt;&lt;/a&gt;&lt;br&gt;
The client sends Refresh Token A.&lt;br&gt;
The server invalidates A and issues Access Token B and Refresh Token B.&lt;br&gt;
Later, the client uses Refresh Token B to obtain the next pair.&lt;br&gt;
Refresh Token A can no longer be used.&lt;br&gt;
Now imagine someone tries to use Refresh Token A again. The server knows that A has already been consumed. This is called refresh token reuse detection. The server can revoke the entire token family and the chain of refresh tokens associated with that login session and require authentication again.&lt;/p&gt;

&lt;p&gt;It cannot reliably determine which party is the attacker. It can only detect that a previously used token has appeared again.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Where to store the refresh token&lt;/strong&gt;&lt;br&gt;
This decides whether all the work above is worth anything. Don’t put tokens in localStorage. Any JavaScript on your page can read it, which means one XSS bug hands over the refresh token. The usual setup is:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Refresh token&lt;/strong&gt;&lt;/em&gt;: httpOnly, secure cookie, so JavaScript can’t read it at all.&lt;br&gt;
&lt;em&gt;&lt;strong&gt;Access token&lt;/strong&gt;&lt;/em&gt;: kept in memory (a plain JavaScript variable) and never written to disk.&lt;br&gt;
Two trade-offs to know about. First, memory is wiped on page reload, so your frontend should quietly call /auth/refresh on startup to get a fresh access token. Second, if your frontend and API sit on different domains, the SameSite=Strict won’t work, and you’ll need SameSite=None plus CSRF protection on the refresh endpoint. On mobile, use the system keychain or keystore instead of a cookie.&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;p&gt;Three production issues you shouldn’t ignore&lt;br&gt;
**&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Network retries: Suppose the server rotates a token, but the response never reaches the client. The client retries with the old token. That can look like token theft.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Design retry handling deliberately. A carefully implemented idempotency mechanism may help, but blindly accepting reused tokens weakens replay detection.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Parallel browser tabs: Two tabs may try to refresh simultaneously. Coordinate refresh operations on the client and enforce atomic token consumption on the server.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Sessions that never expire: If each rotation extends the expiry by another seven days, an active session could continue indefinitely. Give each token family an absolute expiration time that rotation cannot extend.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Also revoke the user’s active token families when their password changes or they explicitly log out, according to your application’s security policy.&lt;/p&gt;

&lt;h2&gt;
  
  
  The takeaway
&lt;/h2&gt;

&lt;p&gt;Refresh token rotation doesn’t make stolen credentials harmless. It gives your server a way to detect the reuse of a previously consumed refresh token and respond by revoking the affected session.&lt;/p&gt;

&lt;p&gt;The important part isn’t just issuing a new token. It’s making token consumption atomic, ensuring revocation actually commits, and handling retries without silently weakening your security.&lt;/p&gt;

&lt;p&gt;A short-lived access token limits exposure. Refresh token rotation helps detect replay. Together, they make a stronger authentication design.&lt;/p&gt;

</description>
      <category>springsecurity</category>
      <category>springboot</category>
      <category>jwttoken</category>
      <category>backend</category>
    </item>
    <item>
      <title>Hibernate vs MyBatis: How Much ORM Magic Do You Actually Want?</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Sun, 04 Oct 2026 16:59:32 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/hibernate-vs-mybatis-how-much-orm-magic-do-you-actually-want-5glc</link>
      <guid>https://dev.to/piyushsingh_dev/hibernate-vs-mybatis-how-much-orm-magic-do-you-actually-want-5glc</guid>
      <description>&lt;p&gt;The query looked harmless. We were fetching a list of orders. The API returned the expected data, the response time looked fine in development, and nothing seemed unusual.&lt;/p&gt;

&lt;p&gt;Then production happened. A single API request was suddenly responsible for executing hundreds of SQL queries. The application wasn’t running a complicated algorithm, and there wasn’t an obvious infinite loop.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fe5ek7e6lwrjlaluaf02n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fe5ek7e6lwrjlaluaf02n.png" alt=" " width="800" height="533"&gt;&lt;/a&gt;&lt;br&gt;
The problem was much simpler: we were accessing a relationship inside a loop. And Hibernate was doing exactly what we had configured it to do. We just hadn’t realized how many database calls that configuration could produce.&lt;/p&gt;

&lt;p&gt;This is one of the reasons I’ve started thinking about Hibernate and MyBatis less as competing persistence frameworks and more as two different philosophies:&lt;/p&gt;

&lt;p&gt;Hibernate gives you more abstraction and automation. MyBatis gives you more visibility and control.&lt;/p&gt;

&lt;p&gt;And that difference becomes especially interesting when you’re debugging database performance.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Real Difference Isn’t “ORM vs SQL”&lt;/strong&gt;&lt;br&gt;
At first glance, Hibernate and MyBatis can look like two tools solving the same problem—both help Java applications talk to relational databases. But they approach it very differently.&lt;/p&gt;

&lt;p&gt;With Hibernate, you generally work with entities and relationships: You don’t necessarily care about the SQL being executed at every step. Hibernate manages much of the persistence behavior for you.&lt;/p&gt;

&lt;p&gt;With MyBatis, you’re much closer to the database, and the SQL is something you explicitly define:&lt;/p&gt;

&lt;p&gt;Neither approach is inherently better. The real question is, how much control do you want the framework to have over your database interactions?&lt;/p&gt;
&lt;h2&gt;
  
  
  Hibernate: Let the Framework Manage Persistence
&lt;/h2&gt;

&lt;p&gt;Hibernate is an ORM—an object-relational mapping framework. Instead of thinking primarily in terms of tables and SQL queries, you work with Java objects:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity
public class Order {
    @Id
    private Long id;

    private BigDecimal amount;

    @ManyToOne(fetch = FetchType.LAZY)
    private Customer customer;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then your repository might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface OrderRepository
        extends JpaRepository&amp;lt;Order, Long&amp;gt; {
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Fetching an order is straightforward, and accessing its customer feels natural:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Order order = orderRepository.findById(orderId)
        .orElseThrow();
String customerName = order.getCustomer().getName();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That’s the beauty of ORM. You think about objects, Hibernate thinks about persistence, and the application code becomes cleaner with a lot of repetitive SQL disappearing. But that abstraction has a cost—sometimes the database is doing more work than the Java code makes obvious.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When Hibernate’s Magic Bites Back&lt;/strong&gt;&lt;br&gt;
Let’s look at a common example. Suppose we fetch 100 orders, then iterate through them:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;Order&amp;gt; orders = orderRepository.findAll();
for (Order order : orders) {
    System.out.println(
        order.getCustomer().getName()
    );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At first glance, this looks like one database operation. But with lazy-loaded relationships, one query fetches the 100 orders, and then every single order.getCustomer() call inside that loop fires its own separate query—100 more, one per order. That's 101 queries for what reads like a two-line loop.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fzv6u9qm23u8f6xwnjlqx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fzv6u9qm23u8f6xwnjlqx.png" alt=" " width="800" height="318"&gt;&lt;/a&gt;&lt;br&gt;
That’s the classic N+1 query problem—I actually wrote a full deep dive on exactly this bug here, if you want the mechanics in more depth. The important point for this article is that Hibernate isn’t necessarily doing something wrong—lazy loading exists for a reason. The problem is that an innocent-looking line like this &lt;strong&gt;order.getCustomer()&lt;/strong&gt; can trigger a database query, and the database interaction is no longer completely obvious from the code. That's where the abstraction can become dangerous.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;But Does MyBatis Solve N+1?&lt;/strong&gt;&lt;br&gt;
Not automatically, and this distinction matters. It’s tempting to say, “MyBatis doesn’t have the N+1 problem"—that's not true. You can absolutely write N+1 queries using MyBatis:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;List&amp;lt;User&amp;gt; users = userMapper.findAllUsers();
for (User user : users) {
    userMapper.findOrdersByUserId(user.getId());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That still results in 1 query to fetch users plus N queries to fetch orders—N+1, the same as before. The difference is where the behavior comes from. MyBatis doesn’t automatically lazy-load a relationship because you accessed a Java property; you explicitly call another mapper method. The database interaction is therefore more visible in your application code. Subtle difference, but an important one.&lt;/p&gt;

&lt;h2&gt;
  
  
  MyBatis: You Own the SQL
&lt;/h2&gt;

&lt;p&gt;MyBatis takes a different approach. Instead of saying, "Here's my object model; figure out how to persist it,” you can say, "Here's the SQL I want to execute; map the result to this Java object."&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;select id="findOrderWithCustomer"
        resultMap="orderResultMap"&amp;gt;
        SELECT
        o.id,
        o.amount,
        c.id AS customer_id,
        c.name AS customer_name
    FROM orders o
    JOIN customers c
        ON o.customer_id = c.id
    WHERE o.id = #{orderId}
&amp;lt;/select&amp;gt;
The Java mapper might look like this:

@Mapper
public interface OrderMapper {
Order findOrderWithCustomer(Long orderId);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the relationship is resolved through a single SQL statement, and there’s much less guessing involved. You decide which tables to join, which columns to select, which indexes matter, how the filtering works, how pagination works, whether a subquery makes sense, and whether a database-specific feature should be used. That control can be extremely valuable, especially when you’re working with complex queries.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Trade-Off: Control Comes With Responsibility&lt;/strong&gt;&lt;br&gt;
There’s a catch. MyBatis doesn’t magically make database access easier—it moves more responsibility toward the developer.&lt;/p&gt;

&lt;p&gt;With Hibernate, you can write orderRepository.findById(orderId) and let the framework handle a lot of persistence details. With MyBatis, you may have to maintain handwritten SQL-like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT
    o.id,
    o.amount,
    o.created_at,
    c.id,
    c.name
FROM orders o
JOIN customers c
    ON o.customer_id = c.id
WHERE o.id = #{orderId};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And when the database schema changes, your SQL may need to change too. When you have dozens or hundreds of queries, SQL maintenance becomes a real concern. This leads to an important observation: Hibernate hides complexity. MyBatis exposes complexity. Neither eliminates it. That’s really the trade-off.&lt;/p&gt;

&lt;h2&gt;
  
  
  Hibernate’s Strength: Productivity
&lt;/h2&gt;

&lt;p&gt;Hibernate shines when your application maps naturally to an object-oriented domain model—think a User with Orders, each with, andItems, and plus Addresses. Managing all of those relationships manually can become tedious, and Hibernate provides abstractions for entity relationships, lazy loading, dirty checking, cascading, transactions, first-level caching, query generation, and object state management. For a typical CRUD-heavy business application, that can save a lot of development time.&lt;/p&gt;

&lt;p&gt;You can modify an entity with, order.setStatus(OrderStatus.PAID); and Hibernate detects the change and generates the appropriate one UPDATE for you. You don't necessarily have to write UPDATE orders SET status = ? WHERE id = ?; yourself. That's a huge productivity advantage.&lt;/p&gt;

&lt;h2&gt;
  
  
  MyBatis’s Strength: Predictability
&lt;/h2&gt;

&lt;p&gt;Now imagine a different type of application—reporting queries involving orders, customers, payments, transactions, aggregations, date ranges, and multiple filters, where the SQL itself might be the most important part of the application. You may need complex joins, window functions, common table expressions, database-specific features, carefully optimized indexes, custom pagination, and precise execution plans.&lt;/p&gt;

&lt;p&gt;In these scenarios, having direct control over SQL can be very useful. Instead of trying to convince an ORM to generate exactly the query you want, you can write the query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;WITH customer_totals AS (
    SELECT
        customer_id,
        SUM(amount) AS total_amount
    FROM orders
    WHERE created_at &amp;gt;= #{startDate}
    GROUP BY customer_id
)
SELECT
    c.id,
    c.name,
    ct.total_amount
FROM customers c
JOIN customer_totals ct
    ON c.id = ct.customer_id
ORDER BY ct.total_amount DESC;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That’s where MyBatis can feel much more natural.&lt;br&gt;
**&lt;br&gt;
Hibernate vs MyBatis: A Different Kind of Abstraction**&lt;br&gt;
Here’s how I think about the difference. With Hibernate, you’re primarily working at the object level—Java objects flow through Hibernate, which generates the SQL, which hits the database. With MyBatis, you’re much closer to the SQL level—your Java code flows through MyBatis, straight into the SQL you wrote yourself, straight to the database.&lt;/p&gt;

&lt;p&gt;Neither is automatically faster. Neither automatically prevents bad queries. And neither eliminates the need to understand databases. That’s an important point: choosing MyBatis doesn’t replace database knowledge. Choosing Hibernate doesn’t remove the need for database knowledge.&lt;/p&gt;
&lt;h2&gt;
  
  
  What About Performance?
&lt;/h2&gt;

&lt;p&gt;This is probably the first question people ask: which one is faster, Hibernate or MyBatis? The honest answer is it depends—there isn’t a universal winner. A well-designed Hibernate application can perform extremely well, and a poorly designed MyBatis application can perform terribly. For example, this MyBatis code can still produce N+1 queries:&lt;/p&gt;

&lt;p&gt;On the other hand, Hibernate can be configured to fetch data efficiently using JOIN FETCHentity graphs, batch fetching, and projections:&lt;/p&gt;

&lt;p&gt;Now the relationship fetches in a single query. The framework doesn’t determine performance by itself—the way we use the framework does.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The Database Still Matters&lt;/strong&gt;&lt;br&gt;
This is where ORM discussions sometimes go wrong. Developers can spend hours debating Hibernate vs. MyBatis while ignoring the more important questions: is the query indexed, what does EXPLAIN it say, and how many rows are actually being scanned? I went deep on exactly this in my indexing article—the short version is that an index is what turns "scan every row" into "jump straight to the match," and that's true no matter which persistence framework sits on top of it. Suppose your query is&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT *
FROM orders
WHERE customer_id = ?
AND status = ?
ORDER BY created_at DESC;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Whether you’re using Hibernate or MyBatis, the database still has to execute that query. If the appropriate index doesn’t exist, changing the Java persistence framework isn’t going to fix the underlying database problem magically. The abstraction layer matters, but the database still matters more.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When Should You Use Hibernate?&lt;/strong&gt;&lt;br&gt;
Hibernate is a strong choice when your application has a rich domain model, CRUD operations dominate, entity relationships are important, you want automatic dirty checking, you want to reduce SQL boilerplate, your team is comfortable with JPA/Hibernate, productivity matters more than having SQL everywhere, and most queries are relatively straightforward. A typical business application can benefit significantly from this approach.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;When Should You Consider MyBatis?&lt;/strong&gt;&lt;br&gt;
MyBatis becomes attractive when SQL is complex, you need precise query control, reporting is a major part of the application, database-specific features are important, you’re working with an existing or legacy database, query performance requires frequent SQL-level tuning, your team is strong in SQL, and you don’t need a heavy ORM abstraction. In these situations, controlling the SQL directly can simplify rather than complicate development.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;And You Don’t Always Have to Choose One&lt;/strong&gt;&lt;br&gt;
This often gets missed in these comparisons. A real application doesn’t have to be Hibernate or MyBatis—it can be both, split by responsibility. Hibernate can handle your normal entity lifecycle: creating an order, updating a payment, and finding a customer. MyBatis can handle complex reports, analytics queries, database-specific SQL, and performance-sensitive reads. The right abstraction can even vary within the same application.&lt;/p&gt;

</description>
      <category>hibernate</category>
      <category>mybatis</category>
      <category>systemdesign</category>
      <category>database</category>
    </item>
    <item>
      <title>How Cache Invalidation Actually Works | Why Your Redis Cache Can Be Fast and Still Be Lying to You</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Sun, 20 Sep 2026 04:20:29 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/how-cache-invalidation-actually-works-why-your-redis-cache-can-be-fast-and-still-be-lying-to-you-398p</link>
      <guid>https://dev.to/piyushsingh_dev/how-cache-invalidation-actually-works-why-your-redis-cache-can-be-fast-and-still-be-lying-to-you-398p</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpq1hkr8j7cybjxo2pmgz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpq1hkr8j7cybjxo2pmgz.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;br&gt;
A user updates their profile picture, hits save, and the page confirms it worked. They refresh to check. The old picture is still there.&lt;/p&gt;

&lt;p&gt;No error. No crash. Nothing in the logs even looks wrong. The write to the database genuinely succeeded; the new picture was sitting right there in the row. But for the next 30 seconds, everyone who loaded that profile, including the user who’d just changed it, saw the old one.&lt;/p&gt;

&lt;p&gt;That’s a scarier kind of bug than a slow query or a hanging request, because nothing looks broken. The app is fast. The database is fine. It’s just quietly, confidently wrong.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;The wrong mental model&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Most people treat caching as the hard part: pick Redis, wrap your read in a try cache, fall back to database block, set a TTL, and ship it. That's the easy 80%.&lt;/p&gt;

&lt;p&gt;The actual hard part is knowing exactly when a cached value stops being true and clearing it out before anyone reads it. There’s an old line in computer science about there only being two genuinely hard problems: cache invalidation and naming things. It gets repeated as a joke, but it’s not really a joke—invalidation is hard because it requires you to know, with certainty, every single place in your codebase that can change the underlying data and make sure every one of them also clears the cache. Miss one write path, anywhere, and you’ve got a bug that only shows up sometimes, which is the worst kind to track down.&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;h2&gt;
  
  
  The three ways people update a cache
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
There are really only three patterns here, and knowing which one you’re using changes what can go wrong.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Cache-aside&lt;/em&gt;&lt;/strong&gt; (also called lazy loading) is the one almost everyone starts with. Your app checks the cache first. On a miss, it reads from the database, then writes that value into the cache for next time. Simple, and it is the most common source of the bug in this article, because nothing automatically tells the cache when the underlying row changes.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;&lt;strong&gt;Write-through&lt;/strong&gt;&lt;/em&gt; writes to the cache and the database at the same time, as one operation. Safer—the cache is never out of sync with the database for longer than that single write takes. The trade-off is every write is now doing two things instead of one, so writes get a little slower.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Write-behind&lt;/em&gt;&lt;/strong&gt; writes to the cache immediately and queues the database update to happen shortly after, asynchronously. Reads and writes both feel instant. The risk is real, though: if your app crashes after the cache write but before the queued database write completes, that update is gone, and the cache and database can end up telling two different stories.&lt;/p&gt;

&lt;p&gt;Most of what follows assumes cache-aside, because it’s what most teams actually use—and it’s the one where you, the developer, are personally responsible for remembering to invalidate.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What actually goes stale, and why TTL doesn’t save you&lt;/strong&gt;&lt;br&gt;
The comforting assumption is, "I set a 5-minute TTL, so worst case, data is 5 minutes old.” That’s true only for a value that never changes during those 5 minutes. It falls apart the moment a write happens in the middle of that window. TTL protects you against forgetting to invalidate, eventually. It does nothing about the gap between a write happening and the next read after it—and that gap is exactly where the user saw their old profile picture, because 30 seconds was well within a much longer TTL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The classic bug, reproduced concretely&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3oywqxh6p7a12l8eupba.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F3oywqxh6p7a12l8eupba.png" alt=" " width="800" height="353"&gt;&lt;/a&gt;&lt;br&gt;
Walk through it as a timeline. Someone changes their profile picture. That write lands in the database successfully. But the code path that handles the update never touches the cache; it only writes to Postgres (or MySQL, or whatever’s underneath) and calls it done. The cache entry for that user, written the last time anyone viewed their profile, just sits there, unaware anything changed. Every read for the rest of its TTL keeps serving that same stale value, confidently, with no error anywhere in the chain.&lt;/p&gt;

&lt;p&gt;This is the single most common shape this bug takes: a write path that updates the source of truth but forgets the cache exists at all.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Race conditions during invalidation&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;There’s a sneakier version of this bug that happens even when someone did remember to invalidate. Two requests interleave:&lt;/p&gt;

&lt;p&gt;Request A checks the cache for a user’s profile—it's a miss, so A starts reading from the database. Before A finishes, request B comes in, updates that same user’s profile in the database, and correctly evicts the cache entry. Then A finishes its database read—with the old data, because it started before B’s write happened—and writes that stale value back into the now-empty cache.&lt;/p&gt;

&lt;p&gt;The cache was invalidated correctly. It got repopulated with stale data anyway, by a read that was already in flight when the write happened. This is why “just add" @CacheEvictisn't a complete answer under real concurrent load—the timing of reads and writes matters, not just whether invalidation code exists.&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;h2&gt;
  
  
  Why cache invalidation is genuinely hard, not just annoying
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
This is worth tying back to how Redis actually works under the hood: being fast was never the hard part. Redis keeps everything in RAM and processes commands on a single thread, making it fast by design—that part’s basically solved for you. What’s not solved for you is knowing every code path in your application that can change the data a cache entry represents and keeping every one of them honest about clearing that entry. A cache doesn’t know when it’s wrong. Something else has to tell it, every single time, from every single place that could make it wrong.&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;h2&gt;
  
  
  Patterns that actually help
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
Keep a short TTL even when you have explicit invalidation. Treat it as a safety net for the invalidation call you’ll eventually forget to add somewhere, not as your primary strategy.&lt;br&gt;
Version your cache keys instead of trying to delete every related key individually. If a product’s price changes, and ten different cache keys reference that product in different ways, bump a version number tied to the product instead of hunting down all ten. Old versions simply age out.&lt;br&gt;
Use event-driven invalidation across services. In a multi-service setup, the service that owns the write often isn’t the one holding the cache. Publishing an event (“user 123 updated”) that any interested service can react to scales a lot better than trying to remember every downstream cache by hand.&lt;br&gt;
&lt;strong&gt;&lt;em&gt;How to detect stale cache bugs in production&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
The quiet ones are the hardest to catch precisely because nothing errors. Two things that actually help:&lt;/p&gt;

&lt;p&gt;Log cache hit or miss alongside the row’s updated_at timestamp. If a cache hit is being served for a row that updated_at is newer than when that cache entry was written, that mismatch is your stale-read bug, made visible instead of silent.&lt;br&gt;
Spot-check critical reads against the database occasionally, especially right after a known write-heavy action, rather than assuming the cache is correct just because it’s returning fast, confident-looking data.&lt;/p&gt;

</description>
      <category>redis</category>
      <category>backend</category>
      <category>softwareengineering</category>
      <category>caching</category>
    </item>
    <item>
      <title>How Database Connection Pooling Actually Works</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Sat, 12 Sep 2026 14:05:43 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/how-database-connection-pooling-actually-works-19d0</link>
      <guid>https://dev.to/piyushsingh_dev/how-database-connection-pooling-actually-works-19d0</guid>
      <description>&lt;p&gt;Two weeks ago I told you about the index that turned a 4-second query into 12 milliseconds. Last week, about the bug that hid behind fifty perfectly fast queries: the N+1 problem. This week’s bug didn’t look like either of those.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbvrju64rhsqa0zrimnbk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbvrju64rhsqa0zrimnbk.png" alt=" " width="800" height="406"&gt;&lt;/a&gt;&lt;br&gt;
The database dashboard was calm. CPU usage was low. Every individual query, when I checked, ran in a few milliseconds. And the app was still hanging — requests sitting there for seconds before anything happened, some timing out completely.&lt;/p&gt;

&lt;p&gt;I kept looking at the database, because that’s where the last two bugs had lived. This one wasn’t there at all. It was sitting one layer up, in the thing that connects your app to the database in the first place.&lt;/p&gt;
&lt;h2&gt;
  
  
  The wrong mental model
&lt;/h2&gt;

&lt;p&gt;Most of us assume that if the database itself isn’t struggling — low CPU, fast queries, nothing ugly in the slow query log — then the app talking to it should be fine too. That assumption is exactly what sends you looking in the wrong place.&lt;/p&gt;

&lt;p&gt;Your app doesn’t open a fresh connection to the database every time it needs one. Opening a raw connection is expensive — a TCP handshake, authentication, session setup — often tens of milliseconds of pure overhead before a single query even runs. So instead, your app keeps a small, fixed set of connections open and ready, and hands them out to requests as needed. That set has a name: a connection pool. And a pool, by definition, has a limit.&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;
&lt;h2&gt;
  
  
  What a connection pool actually does
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
Think of it as a small number of taxis waiting outside a building, instead of every person who needs a ride calling their own car from across town. When your app starts up, it opens a handful of connections to the database up front and keeps them alive. When a request needs to run a query, it “borrows” one of those already-open connections, uses it, and hands it back the moment it’s done — ready for the next request to borrow.&lt;/p&gt;

&lt;p&gt;This is faster for almost every request, because nobody’s waiting on a fresh TCP handshake. It only becomes a problem when more requests want a connection at the same moment than connections are sitting in the pool.&lt;/p&gt;
&lt;h2&gt;
  
  
  What happens when the pool is exhausted
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F6r7zctl454nw9biggf21.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F6r7zctl454nw9biggf21.png" alt=" " width="800" height="377"&gt;&lt;/a&gt;&lt;br&gt;
Say your pool has 10 connections, and 50 requests hit your app in the same second, each one needing to talk to the database. What happens to request number 11?&lt;/p&gt;

&lt;p&gt;Take five seconds and guess before you read on. A lot of people assume the pool scales up automatically, or that request 11 fails right away. Neither is true. Request 11 waits — quietly, in a queue — for one of those 10 connections to be returned by whichever request finishes first. If it waits too long, it doesn’t fail with a database error at all. It fails with something like “connection is not available, request timed out” — an error about the pool, not the database.&lt;/p&gt;

&lt;p&gt;A connection pool is a waiting line with a fixed number of open counters. As long as the number of requests needing a connection at any given moment stays at or below the pool size, everyone gets served instantly, and the whole thing is invisible. That’s exactly why this bug, like the last one, doesn’t show up in development — locally, you’re one person clicking around, rarely more than 2 or 3 concurrent requests, so a pool of 10 looks infinite. It only stops looking infinite once real traffic shows up.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The N+1 connection&lt;/strong&gt;&lt;br&gt;
This is worth calling out directly, because it ties straight back to last week: a request stuck in an N+1 loop, running 50 queries instead of 1, holds its connection roughly 50 times longer than a request that only needs one query. Every extra millisecond a connection stays checked out is a millisecond it’s not available for the next request in line.&lt;/p&gt;

&lt;p&gt;Fixing N+1 doesn’t just cut your query count. It also frees up connections faster, which means your existing pool can serve more concurrent traffic without you touching the pool size at all. These two bugs compound each other more than most people realize — a slow, chatty endpoint doesn’t just look bad in its own logs; it steals capacity from every other endpoint sharing that same pool.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Reproduce pool exhaustion with Spring Boot&lt;/strong&gt;&lt;br&gt;
If you’re on Spring Boot, HikariCP is your default pool, and you can deliberately break this to feel it firsthand. Set this absurdly low in application.properties:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;spring.datasource.hikari.maximum-pool-size=2&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
Then fire several requests at an endpoint that hits the database, at the same time — something like:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;ab -n 20 -c 10 &lt;a href="http://localhost:8080/your-endpoint" rel="noopener noreferrer"&gt;http://localhost:8080/your-endpoint&lt;/a&gt;&lt;/em&gt;&lt;/strong&gt;&lt;br&gt;
That’s Apache Bench: 20 total requests, 10 of them fired concurrently. Watch response times spike, and if you push the concurrency higher, watch requests start failing with a pool timeout instead of a database error. That’s the exact failure mode, produced on purpose, in a few seconds — a much faster way to build intuition for this than reading about it.&lt;/p&gt;
&lt;h2&gt;
  
  
  How HikariCP behaves
&lt;/h2&gt;

&lt;p&gt;HikariCP doesn’t fail loudly the moment the pool runs out. It queues the waiting request and gives it a fixed amount of time — controlled by connection-timeout30 seconds by default — to get a connection before giving up. Only after that timeout expires does it throw, usually something like SQLTransientConnectionException: Connection is not available, request timed out after 30000ms.&lt;/p&gt;

&lt;p&gt;That 30-second default is worth a moment of thought. It means a pool exhaustion problem doesn’t show up as an instant, obvious failure. It shows up as requests that hang for up to 30 seconds before eventually erroring out — which, from a user’s perspective, is often worse than a fast, clean failure would have been. This is also why HikariCP exposes live metrics for active, idle, and pending connections — pending specifically counts requests currently stuck waiting in that queue, and it's the single most useful number for catching this before users do.&lt;/p&gt;
&lt;h2&gt;
  
  
  Why “just increase the pool” is dangerous
&lt;/h2&gt;

&lt;p&gt;The instinctive fix is “make the pool bigger.” That works for a while, and then quietly creates a new problem: your database also has a hard limit on total concurrent connections, and it’s usually smaller than people expect. Every connection your database holds open costs it memory and scheduling overhead, whether or not that connection is doing any work right now — so a database that’s comfortable with 100 connections can genuinely slow down if you push it to 500, even if none of those 500 are running expensive queries.&lt;/p&gt;

&lt;p&gt;There’s a well-known starting formula from HikariCP’s own documentation: roughly ((core_count * 2) + effective_spindle_count). For a lot of standard setups that lands somewhere around 10, not hundreds — which surprises almost everyone the first time they see it, because it feels far too small for a busy app. The real fix usually isn't "bigger pool." It's "correctly-sized pool, plus fixing whatever's holding connections too long" — which, again, often means checking for N+1 queries and slow, unindexed lookups before you ever touch the pool size setting.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pool size × application instances&lt;/strong&gt;&lt;br&gt;
Here’s the multiplication that catches people off guard. Pool size isn’t a global setting — it’s per instance of your app. If you run 10 instances behind a load balancer, and each one has a pool of 50, your database isn’t seeing 50 connections. It’s seeing up to 500, all at once, from a single service.&lt;/p&gt;

&lt;p&gt;This is the most common way teams accidentally overwhelm their database while scaling out to “improve performance.” Adding more app instances to handle more traffic feels like it should only help — but if each new instance brings its own full-size pool, you’re multiplying connection pressure on the database at the same time you’re adding capacity everywhere else. The math to do before scaling out is simple: pool size per instance × number of instances should stay comfortably under your database's actual connection limit, with room left for migrations, admin tools, and anything else that connects directly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to detect pool exhaustion&lt;/strong&gt;&lt;br&gt;
Watch pool metrics, not just database metrics. If you’re using Spring Boot Actuator with Micrometer, HikariCP exposes hikaricp.connections.active, hikaricp.connections.idle, and hikaricp.connections.pending. A pending count that's regularly above zero under normal traffic is your pool telling you it's undersized, well before anything times out.&lt;br&gt;
Load test with realistic concurrency, not realistic query speed. A single slow request rarely reveals pool exhaustion. Ten or twenty requests arriving at the same moment does — because that’s the actual shape of the problem.&lt;br&gt;
Alert on connection timeout exceptions specifically, separate from general 500 errors. A spike in SQLTransientConnectionException is a distinct signal from a spike in application errors, and it points straight at the pool instead of sending you hunting through unrelated code.&lt;br&gt;
How to size the pool&lt;br&gt;
Start from your database’s real connection limit, work backwards, and treat every number as deliberate rather than copy-pasted from a tutorial:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=10
spring.datasource.hikari.connection-timeout=30000
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;maximum-pool-size should come from the HikariCP formula above as a starting point, then get adjusted based on actual load testing, not guesswork. minimum-idle equal to the max keeps a fixed set of connections always warm, which HikariCP's own docs recommend for predictable performance. connection-timeout Controls how long a request will wait in the queue before failing — lower it if you'd rather fail fast and show an error than have users stare at a spinner for 30 seconds.&lt;/p&gt;

&lt;p&gt;Remember while you do this: whatever number you land on here gets multiplied by every instance of your app that’s running.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How the N+1 Query Problem Actually Works | Why Your API Gets Slower With Every Row You Add</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Sun, 30 Aug 2026 04:37:03 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/how-the-n1-query-problem-actually-works-why-your-api-gets-slower-with-every-row-you-add-akk</link>
      <guid>https://dev.to/piyushsingh_dev/how-the-n1-query-problem-actually-works-why-your-api-gets-slower-with-every-row-you-add-akk</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhejd0rducdfmz71k1g0m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fhejd0rducdfmz71k1g0m.png" alt=" " width="800" height="406"&gt;&lt;/a&gt;&lt;br&gt;
Last week I told you about how the day-one line that &lt;strong&gt;CREATE INDEX idx_users_email ON users(email);&lt;/strong&gt; took a query from 4 seconds down to 12 milliseconds. This week's bug was sneakier. There was no slow query to find. When I checked the logs, every single query ran in under 2 milliseconds. Fast, fast, fast, fast — fifty times in a row. The endpoint was still crawling, and for a while I genuinely couldn't figure out why, because I kept looking for the one slow query that wasn't there.&lt;/p&gt;

&lt;p&gt;The problem wasn't one slow query. It was fifty fast ones that had no business existing in the first place.&lt;/p&gt;
&lt;h2&gt;
  
  
  The wrong mental model almost everyone starts with
&lt;/h2&gt;

&lt;p&gt;Most of us assume that if every individual database call is fast, the endpoint built on top of it must be fast too. That feels obviously true. It isn't.&lt;/p&gt;

&lt;p&gt;An endpoint that runs 50 queries at 2 milliseconds each can lose to one that runs a single query at 30 milliseconds—because every query also pays a small "toll" just to travel between your app and the database before it even starts working. Fifty small tolls add up faster than people expect.&lt;/p&gt;
&lt;h2&gt;
  
  
  Quick gut-check before we go further
&lt;/h2&gt;

&lt;p&gt;Say you fetch 20 blog posts, and for each post you also need the author's name. Your code looks something like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const posts = await db.query('SELECT * FROM posts LIMIT 20');
for (const post of posts) {
  post.author = await db.query('SELECT * FROM users WHERE id = ?', [post.author_id]);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;How many queries actually hit the database when this runs?&lt;/p&gt;

&lt;p&gt;Take five seconds and guess before you scroll on. Most people say "20"; the real number is 21, and that gap between what you'd guess and what actually happens is the whole problem, in miniature.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What's actually happening&lt;/strong&gt;&lt;br&gt;
That first query gets your 20 posts — that's the "1" in N+1. Then, for every single post, your loop fires off a separate query to grab that post's author — that's the "N." Twenty posts, twenty extra queries, twenty-one total. Bump it to 500 posts on a busier page, and you're now running 501 queries to render one screen.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fk2qmviqtq0wd937vk47p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fk2qmviqtq0wd937vk47p.png" alt=" " width="800" height="318"&gt;&lt;/a&gt;&lt;br&gt;
Here's what makes this bug so easy to miss: it's invisible in development. With 5 posts in your local database, nobody notices 6 queries firing instead of 1 — it still feels instant. The bug only becomes visible in production, with real data, under real load, which is exactly the worst time to discover it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why ORMs make this worse, not better
&lt;/h2&gt;

&lt;p&gt;This bug rarely shows up in raw SQL. It shows up in ORMs like Hibernate because they're built to make relationships feel effortless. You write, post.author.name and it just works, no query in sight. But behind that one line, the ORM is quietly running a fresh query the moment you touch.author, for every post, every single time. The code looks completely innocent. That's exactly why this is one of the most common performance bugs in real production apps, not a beginner-only mistake.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;A real before-and-after&lt;/strong&gt;&lt;br&gt;
On a dashboard page, we listed 50 posts, and for each one, showed the author's name and a comment count. Nobody had written it maliciously—it was just three lines inside a loop that each felt harmless on their own. Query logging told a different story: 101 queries for a single page load. One for the posts, fifty for the authors, fifty for the comment counts.&lt;/p&gt;

&lt;p&gt;The fix took under twenty minutes. We batched the author lookups into a single WHERE id IN (...) query and did the same for comment counts using a GROUP BY post_id. That brought it down to 3 queries total—one for posts, one for authors, and one for comment counts. Response time on that endpoint dropped, and none of the actual business logic changed. Just how many round trips it took to get the same data.&lt;/p&gt;

&lt;p&gt;That's usually how N+1 fixes go. Small change in code, big change in a number nobody was watching.&lt;/p&gt;

&lt;h2&gt;
  
  
  The fix and the trade-off nobody mentions
&lt;/h2&gt;

&lt;p&gt;The fix is almost always some form of "ask for everything up front instead of asking one item at a time." In SQL, that's a JOIN. In most ORMs, it's a method with a name like .include(), .with(), .select_related(), or @EntityGraph all doing the same thing: telling the ORM, "Fetch the related data in the same trip; don't make me ask for it later."&lt;/p&gt;

&lt;p&gt;But joining isn't automatically free either. If one post has 40 comments, a naive join duplicates that post's data 40 times in the result set—trading fewer round trips for a wider, heavier response. For one-to-one relationships, like a post and its single author, a join is usually a clear win. For one-to-many relationships, like a post and its comments, batching one query for posts, one query for "all comments where post_id IN (...)" often beats a join, because it avoids that duplication entirely.&lt;/p&gt;

&lt;h2&gt;
  
  
  Catching it before it ships
&lt;/h2&gt;

&lt;p&gt;The cheapest place to fix an N+1 is before it ever reaches production, and it doesn't take fancy tooling:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Watch for database calls inside loops.&lt;/strong&gt; Any time you see await or .find() sitting inside a for, map, or forEach over a list, stop and check what it's actually doing.&lt;br&gt;
&lt;strong&gt;Add a query-count assertion to your tests.&lt;/strong&gt; Most frameworks let you count queries per request in a test environment. A simple test that fails if a request fires more than, say, 5 queries will catch most N+1s before a human ever has to notice.&lt;br&gt;
&lt;strong&gt;Use a detector if your framework has one.&lt;/strong&gt; Rails has the bullet gem. Django has django-silk even a basic middleware that logs total query count per request and flags anything unusually high works surprisingly well.&lt;br&gt;
&lt;strong&gt;Read PRs with this specific question in mind:&lt;/strong&gt; "If this list has 500 items instead of 5, what happens?" That single question catches more N+1s in code review than almost anything else.&lt;br&gt;
Once you've hunted one N+1 down, you start seeing the same shape everywhere: a loop that quietly means "go ask the database again." It's one of those bugs that, once you can see them, you can't stop seeing. In a good way. If you haven't already, the &lt;a href="https://medium.com/@singh.piyush/how-database-indexing-actually-works-b-trees-slow-count-and-the-trade-off-nobody-warns-you-a4d5d5142586?sharedUserId=singh.piyush" rel="noopener noreferrer"&gt;indexing article&lt;/a&gt; this one follows on from is worth reading first; a lot of what makes batching and joins fast comes down to the same B-tree fundamentals.&lt;/p&gt;

</description>
      <category>backenddevelopment</category>
      <category>database</category>
      <category>systemdesign</category>
      <category>apidesign</category>
    </item>
    <item>
      <title>How Database Indexing Actually Works | B-Trees, Slow COUNT(*), and the Trade-off Nobody Warns You About</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Sun, 16 Aug 2026 04:44:50 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/how-database-indexing-actually-works-b-trees-slow-count-and-the-trade-off-nobody-warns-you-3bbm</link>
      <guid>https://dev.to/piyushsingh_dev/how-database-indexing-actually-works-b-trees-slow-count-and-the-trade-off-nobody-warns-you-3bbm</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9gomn2uxnqoj5gcvz27q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F9gomn2uxnqoj5gcvz27q.png" alt=" " width="800" height="400"&gt;&lt;/a&gt;&lt;br&gt;
A few years into my backend career, a senior engineer looked at a query I’d written, added one line — CREATE INDEX idx_users_email ON users(email); — and a query that took 4 seconds started returning in 12 milliseconds.&lt;/p&gt;

&lt;p&gt;I remember feeling two things at once. Relief, because the page finally loaded. And a quiet kind of annoyance, because I didn’t actually understand what had just happened. I just knew “add an index, things get fast” — which is the database equivalent of knowing that turning a key starts a car without knowing anything about the engine.&lt;/p&gt;

&lt;p&gt;That gap followed me for years. So this is the explanation I wish someone had given me back then.&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;The wrong mental model almost everyone starts with&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Most people think an index is basically a shortcut list — like the database keeps a separate, smaller copy of your table sorted by whatever column you indexed, and it just checks that instead.&lt;/p&gt;

&lt;p&gt;That’s close, but it’s not quite right, and the gap between “close” and “right” is exactly why indexes sometimes don’t help, sometimes slow down your writes, and sometimes get ignored by the database entirely even when you added one.&lt;/p&gt;
&lt;h2&gt;
  
  
  Quick gut-check before we go further
&lt;/h2&gt;

&lt;p&gt;Say you have a table of 10 million users, and you index the email column. Then you run this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT * FROM users WHERE email LIKE '%gmail.com';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Will the index help here? Take five seconds before you scroll past this. Most people guess yes. The real answer is no — and by the end of this you’ll know exactly why.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What a table actually looks like without an index&lt;/strong&gt;&lt;br&gt;
Picture your table as a stack of index cards thrown in a shoebox, in whatever order they happened to be added. No sorting, no structure. When your database runs a query without an index, it does something called a full table scan — it picks up every single card, checks it against your WHERE clause, and puts it back down.&lt;/p&gt;

&lt;p&gt;For 100 rows, that’s fine. Nobody notices 100 comparisons. For 10 million rows, that’s 10 million comparisons for a query that might only match one row. That’s your 4-second query.&lt;/p&gt;
&lt;h2&gt;
  
  
  What an index actually is
&lt;/h2&gt;

&lt;p&gt;Here’s the part most explanations skip. An index isn’t a copy of your data sitting off to the side. It’s a separate data structure — almost always a B-tree — built specifically to answer one question quickly: “where does this value live?”&lt;/p&gt;

&lt;p&gt;Think of it less like a shortcut list and more like the index at the back of a thick textbook. The book’s pages aren’t reordered. But the index tells you exactly which page to flip to, so you skip straight there instead of reading the whole book front to back.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fei0i0d4ejny284np7bsc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fei0i0d4ejny284np7bsc.png" alt=" " width="800" height="341"&gt;&lt;/a&gt;&lt;br&gt;
A B-tree does this by staying sorted and balanced. Every time you search it, you start at the root, and at each step the tree tells you “go left” or “go right” based on how your value compares to what’s stored there. Instead of checking every row, you’re checking a handful — for 10 million rows, an index typically needs to make around 20–25 comparisons to find your match, not 10 million.&lt;/p&gt;

&lt;p&gt;That’s the entire reason your query went from 4 seconds to 12 milliseconds. Not magic. Just a smarter shape for the data.&lt;/p&gt;
&lt;h2&gt;
  
  
  Try it yourself
&lt;/h2&gt;

&lt;p&gt;If you’ve got a Postgres or MySQL database handy, run this on a decent-sized table:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;EXPLAIN ANALYZE SELECT * FROM your_table WHERE some_column = 'some_value';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Look for the words “Seq Scan” (sequential scan — no index used) versus “Index Scan.” Then add an index on that column and run the same query again. Watch the plan change. This is the single best way to actually feel what’s happening instead of just reading about it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why your gut-check answer was probably wrong&lt;/strong&gt;&lt;br&gt;
Back to that LIKE '%gmail.com' query. A B-tree index is sorted, which means it's brilliant at answering "give me everything that starts with G" — but your search pattern started with a wildcard (%). There's no way to binary-search your way to "somewhere in the middle, containing this text." The database can't use the sorted structure at all, so it falls back to scanning everything anyway. Same for functions wrapped around your column, like WHERE LOWER(email) = 'x' — unless you've built a special index for that exact expression, the regular index is invisible to that query.&lt;/p&gt;

&lt;p&gt;This is the part nobody warns you about: an index only helps the query shapes it was built for. Slapping an index on a column doesn’t mean every query touching that column gets fast. It means queries that search, sort, or filter on that column in a way the tree can actually use get fast.&lt;/p&gt;

&lt;h2&gt;
  
  
  The trade-off nobody mentions in the tutorials
&lt;/h2&gt;

&lt;p&gt;Indexes aren’t free. Every time you insert, update, or delete a row, the database also has to update every index on that table to keep it sorted and balanced. A table with one index writes a little slower. A table with eight indexes because someone added one for every column “just in case” writes noticeably slower — sometimes painfully so.&lt;/p&gt;

&lt;p&gt;This is why senior engineers don’t just index everything. Every index is a bet: you’re trading slower writes for faster reads on that specific column, in that specific pattern. Good indexing is knowing which bets are worth making.&lt;/p&gt;

&lt;p&gt;An index is a separate, sorted structure (usually a B-tree) built to answer “where is this value” fast — not a copy of your table&lt;br&gt;
Without one, the database checks every row, one by one, until it either finds a match or runs out of rows&lt;br&gt;
Indexes only help query patterns they’re built for — leading wildcards and wrapped columns often can’t use them at all&lt;br&gt;
Every index speeds up reads but slows down writes, so adding one is a trade-off, not a free win&lt;/p&gt;

</description>
      <category>database</category>
      <category>systemdesign</category>
      <category>sql</category>
      <category>backenddevelopment</category>
    </item>
    <item>
      <title>Method-Level Security in Spring Security — How @PreAuthorize Actually Works Inside</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Mon, 20 Jul 2026 08:19:11 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/method-level-security-in-spring-security-how-preauthorize-actually-works-inside-7k</link>
      <guid>https://dev.to/piyushsingh_dev/method-level-security-in-spring-security-how-preauthorize-actually-works-inside-7k</guid>
      <description>&lt;p&gt;In the first three parts of this series, every security decision happened before your controller ran.&lt;/p&gt;

&lt;p&gt;The filter chain intercepted the HTTP request. JWT validation proved who you were. OAuth2 handed off your identity from Google. All of it — every authentication check, every URL-level access rule — happened at the HTTP boundary, before a single line of your business logic executed.&lt;/p&gt;

&lt;p&gt;That’s a solid foundation. But it has a gap that URL patterns can’t fill.&lt;/p&gt;

&lt;p&gt;Consider this: &lt;strong&gt;.requestMatchers("/invoices/&lt;/strong&gt;").hasRole("USER")** Lets any authenticated user hit any invoice endpoint. But what if User A should only see their own invoices, not User B's? The URL pattern /invoices/4521 doesn't know who created invoice 4521. You need to be inside the method, with access to the arguments or the return value, to make that ownership decision.&lt;/p&gt;

&lt;p&gt;That’s the problem method-level security solves. And it’s why it exists as a completely separate layer from the filter chain.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Enabling it — and why it’s off by default&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Method-level security is disabled by default. You have to opt in:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Configuration&lt;/span&gt;
&lt;span class="nd"&gt;@EnableMethodSecurity&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;SecurityConfig&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;// rest of your config&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Why off by default? Because enabling it causes Spring to create AOP proxies around every bean with a security annotation. That adds startup overhead and a small per-call interception cost. If you don’t need it, you don’t pay for it. Spring’s design philosophy is explicit opt-in for features that have a cost.&lt;/p&gt;

&lt;p&gt;One thing worth knowing if you’re reading older code: @EnableMethodSecurity replaced @EnableGlobalMethodSecurity(prePostEnabled = true) in Spring Security 6. If you see the old annotation in a codebase, it still works, but it's deprecated. Don't use it for new projects — the behaviour is slightly different, and the new API is cleaner.&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;h2&gt;
  
  
  What Spring actually does when it sees @PreAuthorize
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
This is where most tutorials stop saying anything useful. They show you the annotation and assume you understand what fires it.&lt;/p&gt;

&lt;p&gt;Here’s what actually happens.&lt;/p&gt;

&lt;p&gt;When your Spring application starts and finds a bean with @PreAuthorize on a method, Spring doesn't modify your class. It creates a proxy object that wraps your bean. From that point on, any other bean in your application that injects InvoiceService actually receives the proxy, not the real service.&lt;/p&gt;

&lt;p&gt;When something calls invoiceService.getInvoice(id), the call hits the proxy first. The proxy hands it to *&lt;em&gt;AuthorizationManagerBeforeMethodInterceptor *&lt;/em&gt;— an AOP advice registered specifically to handle @PreAuthorize. This interceptor is the component that actually does the security check.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fn7d0oz3t91k0xq690m7w.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fn7d0oz3t91k0xq690m7w.png" alt=" "&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The interceptor goes to SecurityContextHolder and retrieves the current Authentication object. If you read Part 2 of this series, this is the same Authentication that your JWT filter stored there. If you read Part 3, it's the same one the OAuth2 login flow stored there. The filter chain populates it. Method security reads it. Same object, same store, different consumers.&lt;/p&gt;

&lt;p&gt;The interceptor then evaluates the SpEL expression — the string inside the annotation — against that authentication. If it returns true, control passes to your real method. If it returns false, AccessDeniedException is thrown, caught by ExceptionTranslationFilter (from Part 1), and the client receives a 403.&lt;/p&gt;

&lt;p&gt;Your actual service code only runs if all of that passes cleanly.&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;SpEL expressions — what you can actually write&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The string inside @PreAuthorize is a Spring Expression Language (SpEL) expression evaluated at runtime. It has access to the current authentication, method arguments, and Spring beans.&lt;/p&gt;

&lt;p&gt;The expressions you’ll use most often in production:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;
&lt;span class="c1"&gt;// Check for a role — Spring prepends "ROLE_" automatically&lt;/span&gt;
&lt;span class="c1"&gt;// This checks for ROLE_ADMIN, not ADMIN&lt;/span&gt;
&lt;span class="nd"&gt;@PreAuthorize&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"hasRole('ADMIN')"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;deleteUser&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt; &lt;span class="o"&gt;...&lt;/span&gt; &lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Check for a specific authority - no prefix added&lt;/span&gt;
&lt;span class="c1"&gt;// Use this for fine-grained permissions&lt;/span&gt;
&lt;span class="nd"&gt;@PreAuthorize&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"hasAuthority('PAYMENT_WRITE')"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;processPayment&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Payment&lt;/span&gt; &lt;span class="n"&gt;p&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt; &lt;span class="o"&gt;...&lt;/span&gt; &lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Access method arguments - the # prefix refers to parameter names&lt;/span&gt;
&lt;span class="c1"&gt;// This is the ownership check URL patterns can't do&lt;/span&gt;
&lt;span class="nd"&gt;@PreAuthorize&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"#userId == authentication.principal.id"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="nf"&gt;getInvoice&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;userId&lt;/span&gt;&lt;span class="o"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;invoiceId&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt; &lt;span class="o"&gt;...&lt;/span&gt; &lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// Call a Spring bean from inside the expression&lt;/span&gt;
&lt;span class="c1"&gt;// @ prefix followed by bean name&lt;/span&gt;
&lt;span class="nd"&gt;@PreAuthorize&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"@invoiceService.isOwner(#id, authentication.name)"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="nf"&gt;getInvoice&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt; &lt;span class="o"&gt;...&lt;/span&gt; &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The difference between hasRole and hasAuthority trips up almost every developer at least once. hasRole('ADMIN') checks for the authority ROLE_ADMIN — Spring prepends the prefix automatically. hasAuthority('PAYMENT_WRITE') checks for the exact string. If you store custom permissions in your authorities list without the ROLE_ prefix, use hasAuthority. If you're working with standard roles granted via ROLE_ conventions, use hasRole.&lt;/p&gt;

&lt;p&gt;The #userId == authentication.principal.id pattern is the most valuable thing method security enables. You can't express "the requested userId matches the logged-in user's id" at the URL-matcher level — but you can express it right here, next to the method that enforces it. That's both more secure (the check is right next to the code it protects) and more readable.&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;h2&gt;
  
  
  @PostAuthorize — when you need the return value
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
@PostAuthorize runs after the method executes. It has access to the return value through the returnObject keyword:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Only return the invoice if the logged-in user owns it&lt;/span&gt;
&lt;span class="nd"&gt;@PostAuthorize&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"returnObject.ownerId == authentication.principal.id"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="nf"&gt;getInvoice&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;invoiceRepository&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;findById&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;orElseThrow&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The use case: you need to fetch a record from the database to know who owns it. You don’t want to run a separate ownership query before the fetch — that’s two queries instead of one. So you fetch it, then check.&lt;/p&gt;

&lt;p&gt;The gotcha — and this one matters: the method always runs. If it has side effects — writing to a database, sending an email, calling an external service — those side effects happen even if @PostAuthorize denies access afterward. Only use @PostAuthorize on read-only operations where running the method and then rejecting the result is safe.&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;h2&gt;
  
  
  Where method security fits — the full picture
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
Parts 1 through 4 have built a three-layer security system. This diagram shows how they connect.&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2slq09gyiq7w81zur5g9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F2slq09gyiq7w81zur5g9.png" alt=" "&gt;&lt;/a&gt;&lt;br&gt;
Layer 1 is the filter chain. It operates at the HTTP boundary, before your controller. FilterChainProxy picks the right SecurityFilterChain. AuthorizationFilter applies URL-level access rules. Requests that fail here never reach your code.&lt;/p&gt;

&lt;p&gt;Layer 2 is authentication. JWT validation via OncePerRequestFilter (Part 2) or OAuth2 login via OAuth2LoginAuthenticationFilter (Part 3) — both populate SecurityContextHolder with the verified identity. This is the layer that answers "who is this person."&lt;/p&gt;

&lt;p&gt;Layer 3 is method security. The AOP proxy intercepts service-layer method calls. @PreAuthorize Reads from the same SecurityContextHolder that Layer 2 populated. Fine-grained, data-aware decisions happen here — decisions that Layer 1 couldn't make because they depend on method arguments or return values, not just URL patterns.&lt;/p&gt;

&lt;p&gt;All three layers share one SecurityContextHolder. Layer 2 writes to it. Layers 1 and 3 read from it. The filter chain and method security are not two separate security systems bolted together. They're two consumers of the same authentication store, operating at different points in the request lifecycle.&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;@Secured and @RolesAllowed — what they are and why @PreAuthorize wins&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Two older annotations you’ll encounter in legacy code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Spring's older annotation — no SpEL, role checks only&lt;/span&gt;
&lt;span class="nd"&gt;@Secured&lt;/span&gt;&lt;span class="o"&gt;({&lt;/span&gt;&lt;span class="s"&gt;"ROLE_ADMIN"&lt;/span&gt;&lt;span class="o"&gt;})&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;deleteUser&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt; &lt;span class="o"&gt;...&lt;/span&gt; &lt;span class="o"&gt;}&lt;/span&gt;

&lt;span class="c1"&gt;// JSR-250 standard - not Spring-specific, same limitations&lt;/span&gt;
&lt;span class="nd"&gt;@RolesAllowed&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"ADMIN"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;deleteUser&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt; &lt;span class="o"&gt;...&lt;/span&gt; &lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;@Secured is Spring-specific, no SpEL. @RolesAllowed is the JSR-250 standard, also no SpEL. Both work for simple role checks. Neither lets you access method arguments, call Spring beans, or check return values.&lt;/p&gt;

&lt;p&gt;@PreAuthorize With full SpEL support does everything both of those do and more. For new code, there's no reason to use either of the older annotations. Enable @EnableMethodSecurity and use @PreAuthorize.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;When NOT to use method-level security — and the proxy trap&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;The self-invocation proxy trap is the most common @PreAuthorize bug in production.&lt;/p&gt;

&lt;p&gt;If a method inside a bean calls another annotated method in the same bean, the proxy is bypassed. The call goes directly to the real object, skipping the AOP interceptor entirely. The @PreAuthorize annotation silently does nothing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;InvoiceService&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;

&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;processAll&lt;/span&gt;&lt;span class="o"&gt;()&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;// This calls the REAL method directly - not the proxy&lt;/span&gt;
        &lt;span class="c1"&gt;// @PreAuthorize on getInvoice will NOT fire&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;getInvoice&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;1L&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
    &lt;span class="nd"&gt;@PreAuthorize&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="s"&gt;"hasRole('ADMIN')"&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;Invoice&lt;/span&gt; &lt;span class="nf"&gt;getInvoice&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;invoiceRepository&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;findById&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;orElseThrow&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The fix: inject the service into itself via Spring (which gives you the proxy), or move the annotated method to a different bean.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Don’t put complex ownership logic in SpEL.&lt;/strong&gt; Calling @userService.isOwner(#id, authentication.name) from inside an annotation is hard to test, hard to debug, and invisible during code reviews. If the expression is more than one condition, extract it into a properly tested method.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Don’t use @PostAuthorize on methods with side effects.&lt;/strong&gt; The method runs regardless. If you can’t afford the side effect when access is denied, use @PreAuthorize with a pre-fetch ownership check instead.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Method security doesn’t replace the filter chain.&lt;/strong&gt; Both layers are needed. The filter chain handles unauthenticated requests — turning them away before they reach any code at all. Method security handles authorisation decisions that require data context the filter chain doesn’t have. They’re complementary layers of the same system, not alternatives to each other.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The series in three sentences&lt;/strong&gt;&lt;br&gt;
The filter chain decides if you can enter the building. JWT or OAuth2 proves who you are at the door. @PreAuthorize decides what rooms you can open once you're inside. Same security context. Three different places it applies.&lt;/p&gt;

</description>
      <category>springsecurity</category>
      <category>java</category>
      <category>springboot</category>
      <category>softwareengineering</category>
    </item>
    <item>
      <title>How Kafka Actually Works — Logs, Partitions, and the Design Decisions Nobody Explains</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Tue, 07 Jul 2026 09:58:16 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/how-kafka-actually-works-logs-partitions-and-the-design-decisions-nobody-explains-f43</link>
      <guid>https://dev.to/piyushsingh_dev/how-kafka-actually-works-logs-partitions-and-the-design-decisions-nobody-explains-f43</guid>
      <description>&lt;p&gt;The first time I used Kafka in production, I treated it like RabbitMQ: a message queue. Produce a message, consumer picks it up, done. The message disappears. That’s how queues work. &lt;br&gt;
That mental model worked — until a downstream payment processor went down for 3 hours, and we had to replay everything it missed. I went to look for the messages.&lt;/p&gt;

&lt;p&gt;They were still there.&lt;br&gt;
That moment is when Kafka actually clicked for me. It is not a queue. The messages do not disappear when consumed. And once that distinction lands, every other design decision Kafka makes becomes logical rather than arbitrary.&lt;/p&gt;
&lt;h2&gt;
  
  
  The commit log — Kafka’s actual storage model
&lt;/h2&gt;

&lt;p&gt;Kafka stores messages in an append-only commit log — a file on disk that only ever grows. Every message gets an offset: a sequential position number starting at zero. When a consumer reads a message, nothing is deleted. The message stays. The consumer’s position pointer simply advances.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0noausx2kgwr8i3mgpd2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0noausx2kgwr8i3mgpd2.png" alt=" " width="800" height="396"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is why two completely independent systems can read the same Kafka topic without interfering with each other. Consumer Group A might be at offset 7. Consumer Group B might be at offset 4. They share the same underlying log but track their own positions independently. If you add a third consumer group next week — a new analytics pipeline, a new audit service — it starts at offset 0 and replays everything from the beginning.&lt;/p&gt;

&lt;p&gt;In a traditional message queue, that’s impossible. The message was already consumed and discarded. In Kafka, the log is the source of truth, and consumers are just readers moving through it at their own pace.&lt;/p&gt;

&lt;p&gt;Now here’s the counterintuitive part. Kafka writes to disk and is still faster than many in-memory message brokers for high throughput. The reason is sequential I/O. Random disk writes are slow — the write head has to seek across the platter. Sequential writes, appending to the end of a file, are fast. Kafka only ever appends. Combined with the OS page cache — which keeps recently written data in RAM automatically — and a zero-copy technique called sendfile() that transfers data directly from the page cache to the network socket without passing through application memory, Kafka achieves throughput that can reach hundreds of thousands of messages per second on commodity hardware.&lt;/p&gt;

&lt;p&gt;The disk is not Kafka’s compromise. It is the design.&lt;/p&gt;
&lt;h2&gt;
  
  
  Topics, partitions, and the order guarantee everyone gets wrong
&lt;/h2&gt;

&lt;p&gt;A topic is a named log — think of it like a database table, but for events. A partition is a shard of that topic stored on a specific broker. More partitions means more parallelism, which means higher throughput.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpm6zb2rlb9imr8c2dtol.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fpm6zb2rlb9imr8c2dtol.png" alt=" " width="800" height="471"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is the part that trips up almost every developer building on Kafka for the first time: Kafka guarantees message order within a partition. It does not guarantee order across partitions.&lt;/p&gt;

&lt;p&gt;If you have a topic with three partitions and a producer sends ten messages for the same user, those messages could land on any partition — round-robin by default. If they scatter across partitions, a consumer might process them out of order.&lt;/p&gt;

&lt;p&gt;The fix is the partition key. You set the message key to something stable — a user ID, an order ID, a transaction ID. Kafka hashes that key and routes all messages with the same key to the same partition, every time. Every message for user-1001 lands on partition 0. Every message for user-2002 lands on partition 1. Order is guaranteed per user, not globally — which is usually exactly what you need.&lt;/p&gt;

&lt;p&gt;This is one of the most important production decisions you make when designing a Kafka-based system, and most tutorials mention it in a single sentence. Getting it wrong means debugging ordering issues at 2 am that only manifest under load, when multiple partitions are being consumed concurrently.&lt;/p&gt;
&lt;h2&gt;
  
  
  Consumer groups: how Kafka scales consumption
&lt;/h2&gt;

&lt;p&gt;A consumer group is a set of consumers that share the work of reading a topic. Kafka assigns each partition to exactly one consumer in the group at any given time. With three partitions and three consumers, each consumer handles one partition. With three partitions and five consumers, two consumers sit idle — you cannot have more active consumers than partitions.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgkl7iggb7ev5qqes2096.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fgkl7iggb7ev5qqes2096.png" alt=" " width="799" height="497"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Each consumer group tracks its own offset for each partition, stored in an internal Kafka topic called __consumer_offsets. When a consumer restarts after a crash, it reads its last committed offset from that topic and resumes exactly where it left off. This is what makes Kafka fault-tolerant — not replication alone, but the combination of durable storage and tracked offsets.&lt;/p&gt;

&lt;p&gt;The production pain point is rebalancing. When a consumer joins or leaves a group — whether through a deployment, a crash, or a scale event — Kafka reassigns partitions across the remaining consumers. During a rebalance, consumption pauses across the entire group. For most workloads, this pause lasts a few seconds. For high-throughput systems with many consumers and frequent deployments, rebalancing can become a significant source of latency spikes — sometimes called a “rebalancing storm.”&lt;/p&gt;

&lt;p&gt;Kafka 4.0’s KIP-848 incremental cooperative rebalancing dramatically reduces this. Instead of stopping all consumers and reassigning all partitions, consumers now transfer partitions incrementally while other consumers continue reading. If you’re seeing rebalancing issues in an older Kafka version, upgrading is one of the most effective fixes available.&lt;/p&gt;
&lt;h2&gt;
  
  
  Replication — how Kafka survives broker failures
&lt;/h2&gt;

&lt;p&gt;Each partition has one leader broker and zero or more follower brokers. All reads and writes go to the leader. Followers replicate the leader’s log passively, staying as close to current as possible. If the leader broker fails, Kafka elects a new leader from the in-sync replica set (ISR) — the brokers that are fully caught up with the leader.&lt;/p&gt;

&lt;p&gt;The replication factor controls how many copies exist. A factor of three means you can lose two brokers and still serve traffic. Most production setups use three.&lt;/p&gt;

&lt;p&gt;The acks producer setting is your durability dial:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Fire and forget — fastest, but you can lose messages
props.put("acks", "0");

// Wait for leader only — fast, safer
props.put("acks", "1");

// Wait for all in-sync replicas — slowest, safest
props.put("acks", "all");
props.put("min.insync.replicas", "2");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In fintech systems, acks=all with min.insync.replicas=2 is the standard. You are waiting for at least two brokers to confirm the write before acknowledging the producer. The added latency — typically 10–30ms — is a fair price for knowing that a single broker failure cannot silently drop a payment event.&lt;/p&gt;

&lt;h2&gt;
  
  
  KRaft — ZooKeeper is finally gone
&lt;/h2&gt;

&lt;p&gt;Before Kafka 4.0, every Kafka cluster depended on ZooKeeper — a separate distributed coordination service — to manage broker metadata, leader elections, and cluster configuration. This meant running and maintaining a separate system alongside Kafka, with its own failure modes and operational complexity.&lt;/p&gt;

&lt;p&gt;In March 2025, Apache Kafka 4.0 shipped. ZooKeeper is gone. KRaft — Kafka’s built-in Raft-based consensus protocol — now manages all cluster metadata directly on a quorum of controller nodes. Simpler deployments, faster failover, fewer moving parts.&lt;/p&gt;

&lt;p&gt;If you are setting up a new Kafka cluster today, there is no ZooKeeper to configure. If you are still running an older version with ZooKeeper, the migration path to KRaft is well-documented, and the upgrade is worth the effort. Any tutorial or architecture diagram that still shows ZooKeeper as a required component is outdated.&lt;/p&gt;

&lt;h2&gt;
  
  
  When NOT to use Kafka
&lt;/h2&gt;

&lt;p&gt;This is the part that saves you from over-engineering.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Don’t use Kafka as a simple job queue&lt;/strong&gt;. If you need tasks processed once by one worker — send an email, resize an image, process a webhook — RabbitMQ or Amazon SQS is simpler and operationally lighter. Kafka’s complexity is only justified when you need replay, multiple independent consumer groups, or throughput above what a traditional queue can handle.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Don’t use Kafka for request-reply patterns&lt;/strong&gt;. Kafka is designed for one-way event streaming. If you need a response to a specific message, you are working against the grain. Use a proper RPC mechanism.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Don’t get your partition count wrong at the start&lt;/strong&gt;. You can increase partitions later, but you cannot decrease them without recreating the topic. And increasing partitions changes the hash-to-partition mapping, which breaks the ordering guarantee for any keys that shift partitions. Plan your partition count upfront based on your expected throughput and consumer count.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Don’t skip idempotent producers&lt;/strong&gt;. Without enable.idempotence=true, network retries can produce duplicate messages. Kafka acknowledges a write, the network drops the response, your producer retries, and the message lands twice. In a payment system, that means double charges. Enable idempotence from day one:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;props.put("enable.idempotence", "true");
props.put("acks", "all");
props.put("retries", Integer.MAX_VALUE);
props.put("max.in.flight.requests.per.connection", "5");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is not optional in fintech. It is the baseline. Kafka is durable not despite writing to disk, but because of it. The commit log is not a compromise — it is the design. Once that clicks, every other Kafka decision makes sense.&lt;/p&gt;

</description>
      <category>kafka</category>
      <category>backend</category>
      <category>java</category>
      <category>springboot</category>
    </item>
    <item>
      <title>How OAuth2 Login Works in Spring Security — The Authorization Code Flow Explained</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Thu, 18 Jun 2026 15:55:32 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/how-oauth2-login-works-in-spring-security-the-authorization-code-flow-explained-14l8</link>
      <guid>https://dev.to/piyushsingh_dev/how-oauth2-login-works-in-spring-security-the-authorization-code-flow-explained-14l8</guid>
      <description>&lt;p&gt;You were redirected to Google. You clicked Allow. You came back logged in. Between those three seconds, six things happened — and most backend developers who have built that button have never traced all of them.&lt;/p&gt;

&lt;p&gt;I know because I was one of them. When I first wired up OAuth2 login, it worked on the first attempt. I was relieved. Then a teammate asked me to explain what the state parameter was for, and I didn't have an answer. The feature worked. The understanding wasn’t there.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyzu2j05u6m1h94scmphs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fyzu2j05u6m1h94scmphs.png" alt=" " width="799" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This article is that explanation — not the config, but the actual flow. What fires, in what order, and where it sits inside Spring Security’s filter chain. If you have read Part 1 of this series on Spring Security internals and Part 2 on JWT with OncePerRequestFilter, this picks up exactly where those left off.&lt;/p&gt;

&lt;h2&gt;
  
  
  OAuth2 is not what most developers think it is
&lt;/h2&gt;

&lt;p&gt;Before tracing the flow, one distinction is worth getting right.&lt;/p&gt;

&lt;p&gt;OAuth2 is an authorization framework, not an authentication protocol. It was designed to let applications access resources on behalf of users — not to verify who a user actually is. When you click “Login with Google,” OAuth2 handles the delegation part: your app is asking Google for permission to act on your behalf. But OAuth2 alone cannot tell your app who you are.&lt;/p&gt;

&lt;p&gt;That is what OpenID Connect (OIDC) does. OIDC is a thin identity layer built on top of OAuth2. It adds the id_token — a JWT that carries the user's identity information. When you use "Login with Google" in a Spring Boot app, you are using both: OAuth2 for the delegation mechanism, OIDC for the identity proof.&lt;/p&gt;

&lt;p&gt;Most developers conflate these two because the Spring Security config handles both transparently. Understanding the distinction matters when things go wrong — because the errors from each layer are very different.&lt;/p&gt;

&lt;h2&gt;
  
  
  The 4 roles — mapped to something you already know
&lt;/h2&gt;

&lt;p&gt;Every OAuth2 explanation starts with four roles. Most explanations define them abstractly, which is why they don’t stick. Map them to Login with Google, and they’re immediately obvious.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbt5vra8gyh7rpleszl6c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbt5vra8gyh7rpleszl6c.png" alt=" " width="800" height="377"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resource Owner&lt;/strong&gt; — you, the user. You own the Google account and the data inside it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Client&lt;/strong&gt; — your Spring Boot application. It wants access to the user’s basic profile on your behalf.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Authorization Server&lt;/strong&gt; — Google’s accounts infrastructure (accounts.google.com). It authenticates the user, shows the consent screen, and issues tokens.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resource Server&lt;/strong&gt; — Google’s userinfo API (googleapis.com). It holds the protected data — the email, name, and profile picture your app actually wants.&lt;/p&gt;

&lt;p&gt;One thing worth noting: in the Login with Google scenario, Google plays both the Authorization Server and the Resource Server. That is common with large identity providers. In your own systems — if you are building an API protected by OAuth2—your Spring Boot application becomes the Resource Server, and a separate authorization server (Keycloak, Okta, Auth0) handles the tokens.&lt;/p&gt;

&lt;h2&gt;
  
  
  The Authorization Code Flow—What Happened During That Redirect
&lt;/h2&gt;

&lt;p&gt;There are several OAuth2 flows. The one you use for web applications — and the only one worth knowing in 2026 — is the Authorization Code Flow. The others (Implicit, Resource Owner Password) are either deprecated or meant for machine-to-machine scenarios.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fw7wpzclb1t5u77xemg0f.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fw7wpzclb1t5u77xemg0f.png" alt=" " width="800" height="682"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is each step:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1 — User clicks Login with Google.&lt;/strong&gt;&lt;br&gt;
Your Spring Boot app constructs a URL pointing to Google’s authorization endpoint, including your client_id, the redirect_uri it wants Google to return to, the scope (what access you're requesting — typically openid profile email), a state parameter (more on this shortly), and response_type=code. The user's browser is redirected to that URL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2 — Google shows the consent screen.&lt;/strong&gt;&lt;br&gt;
Google authenticates the user (if not already logged in) and shows them what your app is requesting access to. The user clicks Allow.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3 — Google redirects back with a code.&lt;/strong&gt;&lt;br&gt;
Google redirects the user’s browser to your redirect_uri with an authorization code appended to the URL. This code is short-lived — typically valid for about 60 seconds — and can only be used once.&lt;/p&gt;

&lt;p&gt;Notice what Google did not send: an access token. The code travels through the browser, which means it passes through browser history, HTTP logs, and referrer headers. Sending the actual token here would be a security hole. The code is intentionally useless on its own.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4 — Your app exchanges the code for tokens.&lt;/strong&gt;&lt;br&gt;
This step happens entirely server-to-server. Your Spring Boot backend takes the code and calls Google’s token endpoint directly — not through the browser. It sends the code along with your client_secret. Google verifies both and issues the tokens.&lt;/p&gt;

&lt;p&gt;This server-to-server exchange is the entire security model of the Authorization Code Flow. The client_secret never touches the browser. The actual token never travels through a URL. The browser only ever saw a short-lived code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5 — Google returns an access token and an ID token.&lt;/strong&gt;&lt;br&gt;
The access_token is what you use to call Google's APIs on the user's behalf. The id_token is an OIDC JWT — it contains the user's identity: their Google ID, email, name, and profile picture. If you read Part 2 of this series, this JWT follows the same structure — header, payload, signature — that OncePerRequestFilter was validating.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 6 — Your app reads the id token, loads the user, and populates the SecurityContext.&lt;/strong&gt;&lt;br&gt;
Spring Security decodes theid_token, extracts the user's details, and stores an authentication object in SecurityContextHolder. From here, the rest of your application sees a fully authenticated user — through @AuthenticationPrincipal, SecurityContextHolder.getContext(), or a principal in your controllers. The same as username-password login.&lt;/p&gt;
&lt;h2&gt;
  
  
  Where OAuth2 plugs into Spring Security’s filter chain
&lt;/h2&gt;

&lt;p&gt;This is the part no other OAuth2 tutorial can show you — because they did not write Part 1 first.&lt;/p&gt;

&lt;p&gt;In Part 1, you traced how FilterChainProxy selects a SecurityFilterChain, how authentication filters extract credentials, how ProviderManager delegates to an AuthenticationProvider, and how everything ends up in SecurityContextHolder.&lt;/p&gt;

&lt;p&gt;OAuth2 does not replace that chain. It extends it with two new filters.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8tsdce4icolxllcorgvw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8tsdce4icolxllcorgvw.png" alt=" " width="800" height="729"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;OAuth2AuthorizationRequestRedirectFilter&lt;/strong&gt; — this fires when a user hits /oauth2/authorization/google (or whichever provider you configured). It builds the full authorization URL — including generating and storing the state parameter — and redirects the user's browser to Google. This is what runs in Step 1 and 2 of the flow above.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;OAuth2LoginAuthenticationFilter&lt;/strong&gt; — this fires when Google redirects back to your /login/oauth2/code/google callback URL. It reads the authorization code from the request, verifies the state parameter, calls Google's token endpoint to exchange the code (Step 4), receives the tokens (Step 5), and creates an OAuth2LoginAuthenticationToken.&lt;/p&gt;

&lt;p&gt;That token then goes to ProviderManager — the same ProviderManager you already know from Part 1. ProviderManager loops through its registered providers, finds OidcAuthorizationCodeAuthenticationProvider, and calls it.&lt;/p&gt;

&lt;p&gt;OidcAuthorizationCodeAuthenticationProvider validates the id_token JWT signature, checks its expiry and claims, and calls OAuth2UserService to load or create your application's user. Then it returns a fully authenticated Authentication object.&lt;/p&gt;

&lt;p&gt;That object goes into SecurityContextHolder. Same destination as username-password login. Different path to get there.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;OAuth2UserService — where your app takes over&lt;/strong&gt;&lt;br&gt;
Spring Security handles everything up to this point automatically. OAuth2UserService is where your application steps in.&lt;/p&gt;

&lt;p&gt;After validating the id_token, Spring Security calls OAuth2UserService.loadUser() to turn Google's user attributes into something your application understands. The default implementation, DefaultOAuth2UserService, fetches the user's profile from Google's userinfo endpoint and returns an OAuth2User with those attributes.&lt;/p&gt;

&lt;p&gt;In most production systems, you need more than that. Google gives you a name and email. Your database has a User entity with an internal ID, roles, preferences, and account status. You override DefaultOAuth2UserService to bridge that gap:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {

    @Autowired
    private UserRepository userRepository;
    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        OAuth2User oAuth2User = super.loadUser(userRequest);
        String email = oAuth2User.getAttribute("email");
        // load or create the user in your own DB
        User user = userRepository.findByEmail(email)
            .orElseGet(() -&amp;gt; createNewUser(oAuth2User));
        return new DefaultOAuth2User(
            Collections.singleton(new SimpleGrantedAuthority(user.getRole())),
            oAuth2User.getAttributes(),
            "email"
        );
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is not an OAuth2 concept — it is a Spring Security hook. But it is where most “Login with Google” implementations actually live. The config wires up the flow. This class decides what your application does with the identity Google hands back.&lt;/p&gt;

&lt;h2&gt;
  
  
  The state parameter — the detail almost everyone skips
&lt;/h2&gt;

&lt;p&gt;Every authorization request your app sends to Google includes a state parameter — a randomly generated value that Spring Security creates and stores in the session. When Google redirects back to your app, it returns that same state value unchanged.&lt;/p&gt;

&lt;p&gt;Your app verifies that the returned state matches the one it stored before doing anything else.&lt;/p&gt;

&lt;p&gt;If you skip this check, an attacker can craft a malicious link that starts a login flow and redirects to your callback with their own authorization code. The victim clicks the link, your app completes the exchange, and the victim is now logged into the attacker’s account — with full access to whatever your app shows an authenticated user.&lt;/p&gt;

&lt;p&gt;This is a CSRF attack against OAuth2. Spring Security handles state generation and validation automatically. You do not need to write this logic. But if you ever build an OAuth2 flow manually — or review one built without a framework — missing state validation is the first thing to check.&lt;/p&gt;

&lt;h2&gt;
  
  
  When NOT to use OAuth2
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Do not use the Implicit Flow&lt;/strong&gt;. It was removed from OAuth2.1. It sent tokens directly in the URL, which means tokens in browser history, server logs, and referrer headers. There is no legitimate reason to use it today.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Do not store access tokens in localStorage&lt;/strong&gt;. XSS vulnerabilities can read localStorage trivially. Use HttpOnly cookies, or keep tokens server-side in the session, where JavaScript cannot touch them.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Do not use OAuth2 when you do not need it&lt;/strong&gt;. If your application has its own user database and no external identity provider, JWT authentication — which you traced in Part 2 — is simpler. You own the entire flow, you are not dependent on a third party’s uptime, and there is no redirect dance to debug. OAuth2 earns its complexity only when the third-party identity or the delegated access to third-party resources is genuinely valuable.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Do not forget token expiry&lt;/strong&gt;. Access tokens are short-lived by design. If you store a token and reuse it without checking expiry, your users will get silent authentication failures at the worst possible moment. Build refresh token logic from the start, not as an afterthought.&lt;/p&gt;

</description>
      <category>springsecurity</category>
      <category>oauth</category>
      <category>springboot</category>
      <category>java</category>
    </item>
    <item>
      <title>https://dev.to/piyushsingh_dev/spring-ai-tool-calling-explained-how-to-give-your-llm-real-superpowers-3g04</title>
      <dc:creator>Piyush Kumar Singh</dc:creator>
      <pubDate>Sat, 06 Jun 2026 14:53:18 +0000</pubDate>
      <link>https://dev.to/piyushsingh_dev/-p7e</link>
      <guid>https://dev.to/piyushsingh_dev/-p7e</guid>
      <description>&lt;div class="ltag__link--embedded"&gt;
  &lt;div class="crayons-story "&gt;
  &lt;a href="https://dev.to/piyushsingh_dev/spring-ai-tool-calling-explained-how-to-give-your-llm-real-superpowers-3g04" class="crayons-story__hidden-navigation-link"&gt;Spring AI Tool Calling Explained | How to Give Your LLM Real Superpowers&lt;/a&gt;


  &lt;div class="crayons-story__body crayons-story__body-full_post"&gt;
    &lt;div class="crayons-story__top"&gt;
      &lt;div class="crayons-story__meta"&gt;
        &lt;div class="crayons-story__author-pic"&gt;

          &lt;a href="/piyushsingh_dev" class="crayons-avatar  crayons-avatar--l  "&gt;
            &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3909333%2Fe0081e0c-5341-42fe-b711-92dafd3e0fdb.jpg" alt="piyushsingh_dev profile" class="crayons-avatar__image" width="720" height="720"&gt;
          &lt;/a&gt;
        &lt;/div&gt;
        &lt;div&gt;
          &lt;div&gt;
            &lt;a href="/piyushsingh_dev" class="crayons-story__secondary fw-medium m:hidden"&gt;
              Piyush Kumar Singh
            &lt;/a&gt;
            &lt;div class="profile-preview-card relative mb-4 s:mb-0 fw-medium hidden m:inline-block"&gt;
              
                Piyush Kumar Singh
                
              
              &lt;div id="story-author-preview-content-3835519" class="profile-preview-card__content crayons-dropdown branded-7 p-4 pt-0"&gt;
                &lt;div class="gap-4 grid"&gt;
                  &lt;div class="-mt-4"&gt;
                    &lt;a href="/piyushsingh_dev" class="flex"&gt;
                      &lt;span class="crayons-avatar crayons-avatar--xl mr-2 shrink-0"&gt;
                        &lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3909333%2Fe0081e0c-5341-42fe-b711-92dafd3e0fdb.jpg" class="crayons-avatar__image" alt="" width="720" height="720"&gt;
                      &lt;/span&gt;
                      &lt;span class="crayons-link crayons-subtitle-2 mt-5"&gt;Piyush Kumar Singh&lt;/span&gt;
                    &lt;/a&gt;
                  &lt;/div&gt;
                  &lt;div class="print-hidden"&gt;
                    
                      Follow
                    
                  &lt;/div&gt;
                  &lt;div class="author-preview-metadata-container"&gt;&lt;/div&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;

          &lt;/div&gt;
          &lt;a href="https://dev.to/piyushsingh_dev/spring-ai-tool-calling-explained-how-to-give-your-llm-real-superpowers-3g04" class="crayons-story__tertiary fs-xs"&gt;&lt;time&gt;Jun 6&lt;/time&gt;&lt;span class="time-ago-indicator-initial-placeholder"&gt;&lt;/span&gt;&lt;/a&gt;
        &lt;/div&gt;
      &lt;/div&gt;

    &lt;/div&gt;

    &lt;div class="crayons-story__indention"&gt;
      &lt;h2 class="crayons-story__title crayons-story__title-full_post"&gt;
        &lt;a href="https://dev.to/piyushsingh_dev/spring-ai-tool-calling-explained-how-to-give-your-llm-real-superpowers-3g04" id="article-link-3835519"&gt;
          Spring AI Tool Calling Explained | How to Give Your LLM Real Superpowers
        &lt;/a&gt;
      &lt;/h2&gt;
        &lt;div class="crayons-story__tags"&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/ai"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;ai&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/springboot"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;springboot&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/llm"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;llm&lt;/a&gt;
            &lt;a class="crayons-tag  crayons-tag--monochrome " href="/t/rag"&gt;&lt;span class="crayons-tag__prefix"&gt;#&lt;/span&gt;rag&lt;/a&gt;
        &lt;/div&gt;
      &lt;div class="crayons-story__bottom"&gt;
        &lt;div class="crayons-story__details"&gt;
            &lt;a href="https://dev.to/piyushsingh_dev/spring-ai-tool-calling-explained-how-to-give-your-llm-real-superpowers-3g04#comments" class="crayons-btn crayons-btn--s crayons-btn--ghost crayons-btn--icon-left flex items-center"&gt;
              

              1&lt;span class="hidden s:inline"&gt;&amp;nbsp;comment&lt;/span&gt;
            &lt;/a&gt;
        &lt;/div&gt;
        &lt;div class="crayons-story__save"&gt;
          &lt;small class="crayons-story__tertiary fs-xs mr-2"&gt;
            6 min read
          &lt;/small&gt;
            
              &lt;span class="bm-initial crayons-icon c-btn__icon"&gt;
                

              &lt;/span&gt;
              &lt;span class="bm-success crayons-icon c-btn__icon"&gt;
                

              &lt;/span&gt;
            
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

&lt;/div&gt;


</description>
    </item>
  </channel>
</rss>
