<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bhagyeshh Jain on Medium]]></title>
        <description><![CDATA[Stories by Bhagyeshh Jain on Medium]]></description>
        <link>https://medium.com/@bhagyeshhjain?source=rss-fc2257201902------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7qIuR2zEXVdPXWKnJ8EJ1A.png</url>
            <title>Stories by Bhagyeshh Jain on Medium</title>
            <link>https://medium.com/@bhagyeshhjain?source=rss-fc2257201902------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:39:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhagyeshhjain/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Java Collections: 8 Pitfalls That Pass Code Review and Fail in Production]]></title>
            <link>https://bhagyeshhjain.medium.com/java-collections-8-pitfalls-that-pass-code-review-and-fail-in-production-8c08e22b767b?source=rss-fc2257201902------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c08e22b767b</guid>
            <category><![CDATA[collections-framework]]></category>
            <category><![CDATA[java-code-optimization]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[collections-in-java]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Bhagyeshh Jain]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 18:01:23 GMT</pubDate>
            <atom:updated>2026-10-10T18:01:23.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3D_CymldeSwxgMR8QhRPlg.gif" /></figure><p>The bugs hiding in List, Map, and Set that don&#39;t show up until real data, real load, or a different JVM run.</p><p>Most Java developers learn the collections framework in their first year and never revisit it. That’s the problem. The basics are easy: ArrayList for lists, HashMap for lookups, HashSet for uniqueness. The bugs live in the details: a &quot;read-only&quot; list that changes under you, a map lookup that silently returns null, a comparator that works for years and then breaks on one large value.</p><p>After years of reviewing Java code, these are the eight pitfalls I see most often. Each one compiles cleanly, looks reasonable in a pull request, and fails later. Each comes with the fix.</p><h3>1. unmodifiableList is a view, not a snapshot</h3><p>The name suggests immutability. It isn’t.</p><pre>List&lt;String&gt; source = new ArrayList&lt;&gt;(List.of(&quot;a&quot;, &quot;b&quot;));<br>List&lt;String&gt; readOnly = Collections.unmodifiableList(source);<br><br>source.add(&quot;c&quot;);<br>System.out.println(readOnly); // [a, b, c]</pre><p>Collections.unmodifiableList() only blocks writes <em>through the wrapper</em>. Anyone holding a reference to the original list can still change what the wrapper shows. If you return one of these from a getter, your &quot;encapsulated&quot; state is still being mutated from the outside.</p><p><strong>Fix:</strong> when you need a real snapshot, copy.</p><pre>// independent, truly immutablejava<br>List&lt;String&gt; snapshot = List.copyOf(source); </pre><p>List.copyOf also avoids a needless copy when the input is already an immutable list. And note that Stream.toList() returns an unmodifiable list too, so you can use it at the end of a pipeline without wrapping.</p><h3>2. Arrays.asList and subList are windows into other data</h3><p>Two methods that regularly surprise people:</p><pre>String[] arr = {&quot;a&quot;, &quot;b&quot;, &quot;c&quot;};<br>List&lt;String&gt; list = Arrays.asList(arr);<br><br>list.set(0, &quot;z&quot;);   // writes through: arr[0] is now &quot;z&quot;<br>list.add(&quot;d&quot;);      // UnsupportedOperationException (fixed size)</pre><p>Arrays.asList is a fixed-size list backed by the array. You can set, but you can&#39;t add or remove, and changes write through to the array.</p><p>subList is similar. It&#39;s a view of the original list, not a copy:</p><pre>List&lt;Integer&gt; all = new ArrayList&lt;&gt;(List.of(1, 2, 3, 4, 5));<br>List&lt;Integer&gt; head = all.subList(0, 2);<br><br>all.add(6);          // structural change to the backing list<br>head.size();         // ConcurrentModificationException</pre><p><strong>Fix:</strong> if you need an independent, mutable list, wrap the result: new ArrayList&lt;&gt;(Arrays.asList(arr)) or new ArrayList&lt;&gt;(all.subList(0, 2)).</p><h3>3. List.of, Set.of, and Map.of are stricter than you think</h3><p>The immutable factory methods are excellent, but they have rules that new HashSet&lt;&gt;() never enforced:</p><ul><li><strong>No nulls.</strong> List.of(&quot;a&quot;, null) throws NullPointerException.</li><li><strong>No duplicates in </strong><strong>Set.of or </strong><strong>Map.of.</strong> Set.of(1, 2, 2) throws IllegalArgumentException. Same for duplicate keys in Map.of.</li><li><strong>Set.of and </strong><strong>Map.of have no stable iteration order.</strong> The order can differ from one JVM run to the next, by design.</li></ul><p>That last one is the nasty one. Code that depends on the iteration order of a Set.of(...) can pass every test on your machine and behave differently in another run.</p><p><strong>Fix:</strong> if order matters, say so in the type. Use List for sequence, LinkedHashSet / LinkedHashMap for insertion order, or TreeSet / TreeMap for sorted order. And if values might be null, don&#39;t pass them to of() at all.</p><h3>4. Mutable keys silently break HashMap</h3><p>A HashMap finds an entry using the key&#39;s hashCode() at the time of insertion. If the key&#39;s hash changes afterward, the entry is still in the map, but you can no longer find it.</p><pre>class UserKey {<br>    String id;<br><br>    UserKey(String id) {<br>      this.id = id; <br>    }<br><br>    @Override <br>    public boolean equals(Object o) {<br>      return o instanceof UserKey k &amp;&amp; k.id.equals(id);<br>    }<br><br>    @Override <br>    public int hashCode() {<br>      return id.hashCode(); <br>    }<br>}<br><br>Map&lt;UserKey, String&gt; map = new HashMap&lt;&gt;();<br>UserKey key = new UserKey(&quot;a&quot;);<br>map.put(key, &quot;value&quot;);<br><br>key.id = &quot;b&quot;;<br>map.get(key);                    // null<br>map.get(new UserKey(&quot;a&quot;));       // also null (wrong bucket for equals)</pre><p>No exception, no warning. The entry is just lost.</p><p><strong>Fix:</strong> make keys immutable. Use String, boxed numbers, enums, or record types. And always override equals and hashCode together.</p><h3>5. Collectors.toMap throws on duplicate keys</h3><p>This one works perfectly until production data contains a duplicate.</p><pre>Map&lt;String, User&gt; byEmail = users.stream()<br>    .collect(Collectors.toMap(User::email, u -&gt; u));<br>// IllegalStateException: Duplicate key ...</pre><p><strong>Fix:</strong> decide what a duplicate means, and say it explicitly with a merge function:</p><pre>Map&lt;String, User&gt; byEmail = users.stream()<br>    .collect(Collectors.toMap(User::email, u -&gt; u, (first, second) -&gt; first));</pre><p>Or, if duplicates are legitimate, you probably wanted groupingBy, which collects all matches into a list:</p><pre>Map&lt;String, List&lt;User&gt;&gt; byDomain = users.stream()<br>    .collect(Collectors.groupingBy(User::domain));</pre><h3>6. Use the Map compound methods, and don&#39;t mutate inside them</h3><p>The old pattern of containsKey, then get, then put is verbose and does the lookup up to three times. Java 8 added methods that do it in one step:</p><pre>// Counting<br>Map&lt;String, Integer&gt; counts = new HashMap&lt;&gt;();<br>for (String word : words) {<br>    counts.merge(word, 1, Integer::sum);<br>}<br><br>// Grouping<br>Map&lt;String, List&lt;String&gt;&gt; groups = new HashMap&lt;&gt;();<br>groups.computeIfAbsent(key, k -&gt; new ArrayList&lt;&gt;()).add(value);</pre><p>There’s one rule to remember: <strong>don’t modify the same map from inside the lambda</strong>. For a HashMap, a computeIfAbsent function that adds to the same map can throw ConcurrentModificationException. Recursive memoization (like Fibonacci with computeIfAbsent) is the classic way to hit this.</p><h3>7. Never compare with subtraction</h3><p>This comparator looks fine and is wrong:</p><pre>items.sort((a, b) -&gt; a.score() - b.score());</pre><p>If the difference exceeds Integer.MAX_VALUE (or goes below MIN_VALUE), it overflows and flips sign. The sort order becomes incorrect for those values, and the bug only appears with extreme data.</p><p><strong>Fix:</strong> use the Comparator helpers. They&#39;re safe and more readable:</p><pre>items.sort(Comparator.comparingInt(Item::score)<br>                     .thenComparing(Item::name));</pre><h3>8. ConcurrentHashMap doesn&#39;t make check-then-act safe</h3><p>Swapping HashMap for ConcurrentHashMap protects the map&#39;s internal structure. It does not protect your logic:</p><pre>// Race condition: two threads can both pass the check<br>if (!cache.containsKey(key)) {<br>    cache.put(key, expensiveLoad(key));<br>}Each call is thread-safe on its own, but the sequence isn&#39;t. Two threads can both see the key as missing and both do the work.<br><br></pre><p>Each call is thread-safe on its own, but the <em>sequence</em> isn’t. Two threads can both see the key as missing and both do the work.</p><p><strong>Fix:</strong> use the atomic operations built for this:</p><pre>cache.computeIfAbsent(key, k -&gt; expensiveLoad(k));<br>cache.merge(key, 1, Integer::sum);</pre><p>Also remember that ConcurrentHashMap rejects null keys and null values, unlike HashMap. Code ported over without that check fails at runtime.</p><h3>Bonus: Java 21 makes first/last access cleaner</h3><p>If you’re on Java 21 or later, sequenced collections give List, Deque, LinkedHashSet, and LinkedHashMap a common set of methods:</p><pre>list.getFirst();<br>list.getLast();      // replaces list.get(list.size() - 1)<br>list.reversed();     // a reversed view</pre><p>Small change, but it removes a lot of index arithmetic. Note that getFirst() and getLast() throw NoSuchElementException on an empty collection.</p><h3>Quick checklist for your next review</h3><ul><li>Is this “unmodifiable” collection a view of something mutable? Use copyOf.</li><li>Are any Arrays.asList / subList results being modified or outliving their source?</li><li>Does any code depend on the iteration order of Set.of / Map.of?</li><li>Are map keys immutable, with matching equals and hashCode?</li><li>Does every toMap have a merge function, or a good reason not to?</li><li>Any containsKey followed by put? Replace with merge or computeIfAbsent.</li><li>Any comparator using subtraction?</li><li>Any check-then-act sequence on a concurrent map?</li></ul><p>None of these are exotic. They’re the gap between knowing the collections API and knowing how it behaves under real conditions. If you’ve been bitten by one that isn’t on this list, I’d like to hear about it in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c08e22b767b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refresh Token Rotation with Reuse Detection: How and Why]]></title>
            <link>https://bhagyeshhjain.medium.com/refresh-token-rotation-with-reuse-detection-how-and-why-bc202c348841?source=rss-fc2257201902------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc202c348841</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Bhagyeshh Jain]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 09:28:24 GMT</pubDate>
            <atom:updated>2026-08-18T09:28:24.452Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical implementation guide from building a production OAuth2/OIDC authorization server with Spring Authorization Server.</em></p><figure><img alt="Diagram showing token rotation: two tokens marked “Rotated,” a third marked “Reused — revoked” with a warning pulse." src="https://cdn-images-1.medium.com/max/1024/1*t-lQPc9uXBJSgDdmQeXtHg.gif" /><figcaption>Rotate on every use. Detect reuse instantly. Revoke the whole chain.</figcaption></figure><h3>Quick refresher: Access Tokens vs Refresh Tokens</h3><p>If you’re new to this, here’s the two-sentence version.</p><p>When you log in to an app, you don’t get one token — you usually get two. An <strong>access token</strong> is a short-lived pass (often valid for just 15–60 minutes) that your app sends with every request to prove “I’m logged in.” A <strong>refresh token</strong> is a longer-lived pass (days or weeks) that your app uses <em>only</em> when the access token expires, to quietly get a new one — without making you type your password again.</p><p>The short life of the access token is a safety feature: even if it leaks, it’s useless soon after. The refresh token is the opposite trade-off — it lives much longer, which is convenient (you stay logged in), but also means it’s a much bigger prize if someone steals it.</p><h3><strong>The problem nobody talks about until it bites them</strong></h3><p>Most tutorials on refresh tokens stop at “here’s how to issue one” and “here’s how to renew it.” Almost none of them ask the harder question: <strong>what happens when a refresh token gets stolen?</strong></p><p>If you’re running a long-lived refresh token — say, valid for 30 days — and an attacker manages to copy it (via a compromised device, a leaked log file, an XSS attack, or a malicious browser extension), that token is now a skeleton key. It doesn’t matter how strong your password policy is or how short your access token lifetime is. The attacker just quietly mints new access tokens whenever they want, for a month, without you ever knowing.</p><p>This is the exact gap that <strong>refresh token rotation with reuse detection</strong> closes. It’s a well-known pattern in OAuth2 security circles (RFC 6819 touches on it, and it’s part of the OAuth 2.0 Security Best Current Practice draft), but production-grade implementations are rarely documented end to end. I built a centralized authorization server for a suite of internal SaaS applications, using Spring Boot 3.5.6, Spring Authorization Server, and PostgreSQL. Here’s how it works and why each piece matters.</p><h3>The core idea: Tokens are single-use, and reuse is a signal</h3><p>Think of a refresh token like a single-use entry code a security guard hands you every time you badge into a building. You use the code to get in, and the guard immediately swaps it for a fresh code to use next time — the old one is now worthless. That’s rotation.</p><p>Now imagine someone copies your code before you get a chance to use it. Later, both you and the copier try to badge in with “your” code. The guard can’t tell who’s legitimate just by looking at the code — but they <em>can</em> notice something’s wrong: a code that was already swapped out is being used again. That’s reuse detection. And the sensible response isn’t just “reject this one code” — it’s “assume every code issued to you during this visit is compromised, and shut them all down.”</p><p>That’s the whole idea. The mechanism has two parts, and both are necessary — one without the other is much weaker.</p><p><strong>1. Rotation.</strong> Every time a refresh token is used to get a new access token, the old refresh token is invalidated and a brand-new refresh token is issued in its place. The client is expected to discard the old one and store the new one. This alone limits the <em>window</em> of usefulness for a stolen token — but it doesn’t stop an attacker who uses it before the legitimate client does.</p><p><strong>2. Reuse detection.</strong> Because tokens are single-use, if the <em>same</em> refresh token is ever presented a second time, that’s not a normal client behaving unusually — it’s a strong signal that two parties now believe they hold a valid token. One of them is the legitimate client. The other is not supposed to exist. When this happens, the entire chain of tokens descended from that session — not just the one token — is revoked immediately.</p><p>That last part is the piece people often miss. If you only revoke the <em>reused</em> token, the attacker can just fall back to the <em>next</em> token in the rotation chain they may have also captured. You have to kill the whole lineage.</p><h3>Modeling the “Token Family”</h3><p>To make this work, a simple valid/invalid flag on each token isn’t enough. You need to know which tokens are related to each other — which ones came from the same original login, one rotation after another.</p><p>I modeled this as a <strong>token family</strong>: think of it as one long chain of tickets, all stamped with the same family ID, going back to the moment you first logged in. Every time a token rotates, it doesn’t start a new chain — it just adds the next link. That shared ID is what lets you revoke the <em>entire</em> chain in one move, instead of hunting down each token individually.</p><p>A simplified shape of what gets persisted:</p><pre>RefreshTokenRecord<br>- id<br>- token_hash          (never store the raw token)<br>- family_id           (shared by every token in the rotation chain)<br>- issued_at<br>- expires_at<br>- revoked_at<br>- revoked_reason      (ROTATED / REUSE_DETECTED / LOGOUT / EXPIRED)<br>- session_id          (links back to the originating session)</pre><p>A few deliberate choices here worth calling out:</p><ul><li><strong>Store a hash, not the actual token.</strong> This is the same idea as never storing plain-text passwords. If your database were ever leaked, you don’t want it to contain anything an attacker could directly reuse. A hash (a scrambled, one-way version of the token) lets you check “does this match?” without ever storing the real thing.</li><li><strong>family_id is what makes bulk revocation easy.</strong> Instead of tracking down every individual token one by one, you can say &quot;revoke everything with this family ID&quot; in a single database update.</li><li><strong>revoked_reason helps you tell security events apart from routine ones.</strong> A session ending because of REUSE_DETECTED (someone stole a token) is very different from a session ending because of LOGOUT (the user just signed out). The first might deserve a &quot;we noticed something unusual&quot; email to the user; the second doesn&#39;t.</li></ul><h3>The rotation flow, step by step</h3><p>When a refresh request comes in:</p><ol><li><strong>Look up the token by hash.</strong> If it doesn’t exist, reject — this is either garbage input or a token that already expired and was purged.</li><li><strong>Check if it’s already revoked.</strong> This is the reuse-detection trigger. If revoked_at is already set, someone is presenting a token that was already consumed. Immediately revoke the <em>entire family</em> (family_id), not just this token, and log a security event. Do not issue new tokens.</li><li><strong>Check expiry.</strong> Standard TTL check, separate from revocation.</li><li><strong>If valid and unused:</strong> revoke this token (revoked_reason = ROTATED), issue a new access token, issue a new refresh token in the <em>same family</em>, and persist it.</li><li><strong>Return the new token pair to the client.</strong></li></ol><p>The critical ordering detail is step 2 happening <em>before</em> any token issuance logic runs. It’s tempting to write this as a single “is this token good, if so proceed” check, but reuse detection has to be its own explicit branch with its own side effect — because a “reused” token is not simply invalid, it’s evidence.</p><h3>What your framework gives you for free — and what it doesn’t</h3><p>If you’re using a framework like Spring Authorization Server (or an equivalent in another language), it already handles a lot of the OAuth2 groundwork for you: generating tokens, validating them, and storing basic authorization records.</p><p>What it typically does <em>not</em> give you out of the box is the “notice reuse and revoke the whole family” behavior described above. That’s business logic you add on top, in the layer that handles refresh requests before new tokens go out. In practice, this means three things:</p><ol><li><strong>You control how tokens get stored and looked up</strong>, so the reuse check (step 2 in the flow above) actually has somewhere to check against.</li><li><strong>You add your family-revocation check as an explicit step</strong>, before the framework’s normal “issue new token” behavior runs.</li><li><strong>You connect this to your logging/notification systems</strong>, so a reuse event doesn’t just quietly revoke tokens in the database — it shows up somewhere a human (or the affected user) can see it.</li></ol><p>That last point matters more than it might seem. A revoked token family should also end whatever “you’re logged in” state the rest of your app is tracking — not just the database row.</p><h3>Why this is worth the extra complexity</h3><p>It’s fair to ask whether this is over-engineering for an internal tool. In my experience, the honest answer is: it’s cheap to build once you’ve modeled the token family correctly, and it converts an entire class of “we have no idea if we’ve been compromised” incidents into “we got an alert the moment it happened.” Refresh tokens are long-lived by design — that’s what makes them convenient, and it’s exactly what makes them dangerous if you have no way to detect misuse.</p><p>The pattern isn’t exotic. It’s one family_id column and one extra branch in your refresh logic. But it&#39;s the difference between a stolen token being a silent, month-long liability and being a security event you catch on first reuse.</p><p><em>This is based on the backend architecture, identity and security, and lessons I learned from building production systems. If you’re working on OAuth2/OIDC infrastructure or have questions about this implementation, I’d love to hear from you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc202c348841" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Partial Updates in Apache Solr]]></title>
            <link>https://bhagyeshhjain.medium.com/partial-updates-in-apache-solr-12cc57d589e1?source=rss-fc2257201902------2</link>
            <guid isPermaLink="false">https://medium.com/p/12cc57d589e1</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[partial-update]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[apache-solr]]></category>
            <category><![CDATA[search-engines]]></category>
            <dc:creator><![CDATA[Bhagyeshh Jain]]></dc:creator>
            <pubDate>Fri, 31 Jul 2026 10:04:02 GMT</pubDate>
            <atom:updated>2026-07-31T17:02:40.686Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<h3>Partial Updates in Apache Solr: How to Modify a Document Without Reindexing Everything</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S84x-p0vN2P0VxJuFTviZQ.png" /></figure><p>If you’ve worked with Solr in production, you already know the pain: a document has 100+ fields, and a business event changes exactly one of them — say, inventory_count or status. Do you really need to re-fetch the entire source record, rebuild the whole document, and push it through your indexing pipeline again just to flip one value?</p><p>No. Solr has supported <strong>partial (atomic) updates</strong> for years, and most teams either don’t know about it or avoid it because of a few sharp edges around field storage. This article walks through what atomic updates are, how to use them, and the gotchas that trip people up in real systems.</p><h4><strong>What “Partial Update” Actually Means in Solr?</strong></h4><p>Solr documents are stored in an inverted index, not as editable rows in a database. There’s no in-place mutation at the storage layer. So when Solr does an “atomic update,” what actually happens under the hood is:</p><ol><li>Solr reads the existing stored values of the document (using the unique key).</li><li>It merges in the fields you specified in your update request.</li><li>It <strong>reindexes the entire document</strong> as a new version internally, replacing the old one.</li></ol><p>This matters because it explains the single biggest constraint you’ll run into: <strong>every field you want to retain must be retrievable</strong>, which usually means it must be stored (stored=&quot;true&quot;) or have docValues enabled. If a field isn&#39;t stored and doesn&#39;t have docValues, Solr can&#39;t reconstruct it during the merge, and it will silently disappear from the document after your &quot;partial&quot; update. This is the single most common bug reports around this feature.</p><h4>The Basic Syntax</h4><p>Atomic updates use special modifier keys instead of plain values in your update JSON. Here’s the core set:</p><figure><img alt="Apache Solr atomic update modifier keys" src="https://cdn-images-1.medium.com/max/1024/1*wzCQAdSZLr8jLNFniGy5lw.png" /></figure><h4><strong>Example: Updating a single field</strong></h4><pre>POST /solr/products/update<br>[<br>  {<br>    &quot;id&quot;: &quot;SKU-10293&quot;,<br>    &quot;inventory_count&quot;: {&quot;set&quot;: 42}<br>  }<br>]</pre><p>This leaves every other field on SKU-10293 untouched — assuming those fields are stored or have docValues.</p><h4>Example: Incrementing a counter</h4><pre>POST /solr/products/update<br>[<br>  {<br>    &quot;id&quot;: &quot;SKU-10293&quot;,<br>    &quot;view_count&quot;: {&quot;inc&quot;: 1}<br>  }<br>]</pre><p>This is genuinely atomic at the document level — useful for things like page-view counters or stock decrements, without a read-modify-write cycle in your application code.</p><h4>Example: Appending to a multivalued field</h4><pre>POST /solr/products/update<br>[<br>  {<br>    &quot;id&quot;: &quot;SKU-10293&quot;,<br>    &quot;tags&quot;: {&quot;add&quot;: &quot;clearance&quot;}<br>  }<br>]</pre><p>Use add-distinct instead of add if you want to avoid duplicate tags</p><pre>POST /solr/products/update<br>[<br>  {<br>    &quot;id&quot;: &quot;SKU-10293&quot;,<br>    &quot;tags&quot;: {&quot;add-distinct&quot;: &quot;clearance&quot;}<br>  }<br>]</pre><h4>Example: Removing a value</h4><pre>POST /solr/products/update<br>[<br>  {<br>    &quot;id&quot;: &quot;SKU-10293&quot;,<br>    &quot;tags&quot;: {&quot;remove&quot;: &quot;clearance&quot;}<br>  }<br>]</pre><h4>Example: Clearing a field</h4><pre>POST /solr/products/update<br>[<br>  {<br>    &quot;id&quot;: &quot;SKU-10293&quot;,<br>    &quot;promo_code&quot;: {&quot;set&quot;: null}<br>  }<br>]</pre><h4>Using curl</h4><p>If you want to test this from the command line before wiring it into application code:</p><pre>curl -X POST http://localhost:8983/solr/products/update?commit=true \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;[{&quot;id&quot;: &quot;SKU-10293&quot;, &quot;inventory_count&quot;: {&quot;set&quot;: 42}}]&#39;</pre><h4>Using SolrJ (Java)</h4><p>Since this is likely part of a Spring Boot service in most enterprise setups, here’s the SolrJ equivalent:</p><pre>SolrInputDocument doc = new SolrInputDocument();<br>doc.addField(&quot;id&quot;, &quot;SKU-10293&quot;);<br><br>Map&lt;String, Object&gt; incMap = new HashMap&lt;&gt;();<br><br>incMap.put(&quot;set&quot;, 42);<br>doc.addField(&quot;inventory_count&quot;, incMap);<br><br>solrClient.add(&quot;products&quot;, doc);<br>solrClient.commit(&quot;products&quot;);</pre><p>If you’re using Map.of() for brevity in Java 21:</p><pre>SolrInputDocument doc = new SolrInputDocument();<br><br>doc.addField(&quot;id&quot;, &quot;SKU-10293&quot;);<br>doc.addField(&quot;inventory_count&quot;, Map.of(&quot;set&quot;, 42));<br><br>solrClient.add(&quot;products&quot;, doc);<br>solrClient.commit(&quot;products&quot;);</pre><h4>Schema Requirements — the Part Everyone Forgets</h4><p>This deserves its own section because it’s the reason atomic updates “randomly break” for people.</p><p>For atomic updates to work correctly, <strong>every field in the document schema must be retrievable</strong>, meaning one of the following must be true for each field:</p><ul><li>stored=&quot;true&quot;, or</li><li>docValues=&quot;true&quot; (and the field type supports it)</li></ul><p>If you have fields that are indexed but not stored and don’t have docValues — common for fields you only use for filtering or faceting and never intended to retrieve — an atomic update will drop them from the document. Solr can’t merge in what it can’t read back.</p><p><strong>The fix:</strong> audit your schema before relying on atomic updates. Either add docValues=&quot;true&quot; to fields that support it (this is cheap for most field types and is increasingly the default in modern Solr schemas anyway), or mark fields stored=&quot;true&quot; if docValues isn&#39;t an option for that type.</p><h4>Copy Fields and Atomic Updates Don’t Mix Well</h4><p>If your schema uses &lt;copyField&gt; to populate a catch-all text_all field for search, be aware: atomic updates re-run the full indexing chain, which means copy fields get regenerated correctly. That part is not the problem. The actual trap is with <strong>derived or computed fields populated at index time by an external process</strong> (e.g., an update processor or client-side enrichment) — those won&#39;t be recomputed by an atomic update unless the logic lives in Solr&#39;s update chain itself. If your enrichment happens in application code before sending the full document, an atomic update will not trigger that enrichment again.</p><h4>Version Conflicts and Optimistic Concurrency</h4><p>If you’re doing partial updates from multiple concurrent processes (increment a counter from several application instances, for example), you should combine atomic updates with Solr’s optimistic concurrency control to avoid lost updates:</p><pre>[<br>  {<br>    &quot;id&quot;: &quot;SKU-10293&quot;,<br>    &quot;_version_&quot;: 1592837465,<br>    &quot;inventory_count&quot;: {&quot;inc&quot;: -1}<br>  }<br>]</pre><p>If the _version_ doesn&#39;t match what&#39;s currently in the index, Solr rejects the update with a 409 conflict, and your application can retry. For simple counters, inc is already atomic at the single-document level within a single request, so you often don&#39;t need this — but for set operations based on read-then-decide logic in your application, it matters.</p><h4>When Partial Updates Are the Wrong Tool</h4><p>A few situations where you’re better off doing a full reindex of the document instead:</p><ul><li><strong>Bulk field renames or schema migrations</strong> — atomic updates don’t help here; you need a full reindex pass regardless.</li><li><strong>Documents where most fields change together</strong> — if 10 of 15 fields change on every update, the overhead of computing a partial update in your application code isn’t buying you much over just sending the full document.</li><li><strong>Nested/child documents</strong> — atomic updates on documents with nested children have historically had rough edges depending on Solr version; test carefully before relying on this in a schema with block-join nesting.</li></ul><h4>Summary</h4><p>Atomic updates in Solr let you modify one or two fields on a document without resending the entire payload, which is a meaningful win for update-heavy fields like counters, status flags, and tags. The mechanism is a read-merge-reindex cycle under the hood, not a true in-place patch, and that has one hard consequence: <strong>every field must be stored or have docValues, or it will be silently dropped</strong>. Get your schema right first, then set, inc, add, and remove become simple, reliable tools rather than a source of mysterious data loss.</p><p><em>If you’re running Solr behind a Spring Boot service, atomic updates pair nicely with </em><em>@Scheduled jobs or event listeners that only need to touch a handful of fields — no need to round-trip the full domain object through your indexing pipeline for a status change.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12cc57d589e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>