[{"data":1,"prerenderedAt":1140},["ShallowReactive",2],{"\u002Farticles\u002Fgeoip-user-country":3},{"id":4,"title":5,"body":6,"date":1125,"description":1126,"extension":1127,"head":1128,"image":1129,"meta":1130,"navigation":378,"ogImage":1128,"path":1131,"rating":345,"readingTime":1132,"robots":1128,"schemaOrg":1128,"seo":1133,"sitemap":1134,"stem":1135,"tags":1136,"__hash__":1139},"articles_en\u002Farticles\u002Fgeoip-user-country.md","No External API, No DDL: How the \"User Country\" Field Grew Out of a Login IP",{"type":7,"value":8,"toc":1103},"minimark",[9,24,29,32,49,63,66,70,75,175,179,182,192,199,208,212,215,231,235,241,248,289,296,305,309,316,491,494,499,506,554,560,565,587,592,595,599,603,613,620,672,679,684,688,695,701,715,719,728,735,739,743,750,762,766,773,781,787,857,868,872,877,888,897,950,959,969,975,989,993,1051,1055,1099],[10,11,12,21],"blockquote",{},[13,14,15,16,20],"p",{},"The operations team wanted to see \"which country is this user from\" on the customer detail page. It sounds like a one-line requirement, but the database had no address field at all. The only thing remotely related to geography was a ",[17,18,19],"code",{},"login_ip"," column that had been sitting there for half a year without anyone writing to it.",[13,22,23],{},"This post documents how the requirement was delivered end to end: a hands-on comparison of four approaches, a zero-DDL design, three hair-pulling pitfalls, and why in the end I still gave it a scheduled job that \"swaps its brain every week\".",[25,26,28],"h2",{"id":27},"_1-breaking-down-the-requirement-it-is-really-two-problems","1. Breaking down the requirement: it is really two problems",[13,30,31],{},"\"Show the user's country on the detail page\" splits into two things:",[33,34,35,43],"ol",{},[36,37,38,42],"li",{},[39,40,41],"strong",{},"Get the user's IP"," — when do we capture it, and where do we store it?",[36,44,45,48],{},[39,46,47],{},"Turn the IP into a country"," — what do we resolve it with?",[13,50,51,52,55,56,59,60,62],{},"The first one is easy to agree on: the IP ",[39,53,54],{},"at login time"," is the most representative (it is backed by an explicit user action), and the login record table ",[17,57,58],{},"login_record"," already had a ",[17,61,19],{}," column lying around. Whoever created the table clearly thought of it; the login flow just never wrote to it.",[13,64,65],{},"The second one is where the real decision-making happens.",[25,67,69],{"id":68},"_2-comparing-the-options-four-roads-three-ruled-out-by-testing","2. Comparing the options: four roads, three ruled out by testing",[71,72,74],"h3",{"id":73},"the-candidates","The candidates",[76,77,78,97],"table",{},[79,80,81],"thead",{},[82,83,84,88,91,94],"tr",{},[85,86,87],"th",{},"Option",[85,89,90],{},"How it works",[85,92,93],{},"Pros",[85,95,96],{},"Fatal flaw",[98,99,100,127,143,159],"tbody",{},[82,101,102,108,119,122],{},[103,104,105],"td",{},[39,106,107],{},"A. Ready-made header from the CDN\u002Fgateway",[103,109,110,111,114,115,118],{},"Cloudflare's ",[17,112,113],{},"CF-IPCountry",", CloudFront's ",[17,116,117],{},"CloudFront-Viewer-Country","; the backend just reads a header",[103,120,121],{},"Zero code, zero dependencies, reusable site-wide",[103,123,124],{},[39,125,126],{},"You need to have a CDN in the first place",[82,128,129,134,137,140],{},[103,130,131],{},[39,132,133],{},"B. Online IP geolocation API",[103,135,136],{},"Call ip-api \u002F ipinfo at login and persist the country",[103,138,139],{},"Least code, data is always current",[103,141,142],{},"External dependency (quota\u002Flatency\u002Favailability), needs DDL, user IPs leave your system for a third party",[82,144,145,150,153,156],{},[103,146,147],{},[39,148,149],{},"C. Local offline database, GeoLite2",[103,151,152],{},"Bundle the mmdb file into the jar and query it in memory",[103,154,155],{},"No outbound calls, no quota, microsecond lookups, zero DDL",[103,157,158],{},"jar grows by 8MB; the data is a snapshot and goes stale",[82,160,161,166,169,172],{},[103,162,163],{},[39,164,165],{},"D. Local offline database, ip2region",[103,167,168],{},"Same as C, with the xdb format instead",[103,170,171],{},"Fully open source, can be committed to the repo",[103,173,174],{},"Country names are Chinese strings (\"美国|0|0|0|0\"), so a bilingual UI still has to maintain its own Chinese-name → ISO-code mapping table",[71,176,178],{"id":177},"ruling-out-option-a-a-pleasant-bit-of-dns-detective-work","Ruling out option A (a pleasant bit of DNS detective work)",[13,180,181],{},"Option A is the most tempting. If there is a CDN at the entry point, this requirement is practically free. Whether it is worth betting on is something you can find out by probing:",[183,184,190],"pre",{"className":185,"code":187,"language":188,"meta":189},[186],"language-text","$ Resolve-DnsName api.example.com\n→ no CNAME pointing to a CDN\n\n$ curl -sI https:\u002F\u002Fapi.example.com\u002F\n→ no cf-ray, no via: cloudfront in the response headers\n","text","",[17,191,187],{"__ignoreMap":189},[13,193,194,195,198],{},"Conclusion: testing confirmed that there is ",[39,196,197],{},"no CDN on the API request path that would inject a geolocation header",". Going with option A would mean adding a geoip2 module to the production entry gateway myself: installing system libraries and changing the entry configuration that all traffic flows through. The risk far outweighs the benefit. Ruled out.",[10,200,201],{},[13,202,203,204,207],{},"A bonus finding along the way: only once you know exactly which hops are on the request path can you decide which part of ",[17,205,206],{},"X-Forwarded-For"," the backend should trust. On our path, taking the real client IP from the head of the chain is reliable.",[71,209,211],{"id":210},"why-option-b-was-ruled-out","Why option B was ruled out",[13,213,214],{},"It is not that an online API cannot work; it is just a bad deal for this scenario:",[216,217,218,225,228],"ul",{},[36,219,220,221,224],{},"You must ",[39,222,223],{},"resolve at login time and persist the result"," (you cannot make an outbound call every time the detail page opens), so you need a DDL change to add a column",[36,226,227],{},"Login is a critical path, so the outbound call has to be asynchronous with timeout fallback, and the code ends up more complex than option C",[36,229,230],{},"The free quota is a hidden ceiling: the free tier of ip-api explicitly forbids commercial use, and the free tier of ipinfo is 50k\u002Fmonth. It is enough today only because the volume is small today",[71,232,234],{"id":233},"the-final-choice-c-geolite2-mmdb-resolve-at-query-time","The final choice: C (GeoLite2 mmdb) + resolve at query time",[236,237,238],"note",{},[13,239,240],{},"GeoLite2 is provided by MaxMind, and using it is subject to MaxMind's license agreement.",[13,242,243,244,247],{},"Besides the data source, there is an orthogonal decision: ",[39,245,246],{},"when to resolve",".",[76,249,250,262],{},[79,251,252],{},[82,253,254,257,259],{},[85,255,256],{},"Timing",[85,258,93],{},[85,260,261],{},"Cons",[98,263,264,275],{},[82,265,266,269,272],{},[103,267,268],{},"Resolve at login → persist the country",[103,270,271],{},"Zero resolution cost on the detail page; can filter\u002Freport by country in SQL",[103,273,274],{},"Needs DDL; after an mmdb upgrade the existing rows hold outdated conclusions",[82,276,277,283,286],{},[103,278,279,282],{},[39,280,281],{},"Resolve in real time at query time"," (✅)",[103,284,285],{},"Zero DDL; historical data is automatically recomputed when the database is replaced; the country is never persisted, so there is no dirty data",[103,287,288],{},"One extra table query per detail request; cannot filter by country in SQL",[13,290,291,292,295],{},"Right now the only consumer is \"display on the detail page\", so I went with resolving at query time. ",[39,293,294],{},"An mmdb is an in-memory prefix tree and a single lookup takes microseconds",", so the cost of computing it on the fly is effectively zero.",[10,297,298],{},[13,299,300,301,304],{},"What is an mmdb? You can think of it as \"an IP → country dictionary shipped inside the bundle\". But it is not JSON; it is a ",[39,302,303],{},"binary trie (prefix tree)"," designed specifically for IP matching. An IP is essentially 32 or 128 bits, and a lookup just walks the tree bit by bit, which is why an 8MB file can cover every IP range in the world and still answer in microseconds.",[25,306,308],{"id":307},"_3-the-design-two-flows-decoupled-by-one-column","3. The design: two flows, decoupled by one column",[13,310,311,312,315],{},"The whole implementation is split by the single column ",[17,313,314],{},"login_record.login_ip"," into two flows that do not interfere with each other:",[183,317,321],{"className":318,"code":319,"language":320,"meta":189,"style":189},"language-mermaid shiki shiki-themes github-light github-dark github-dark","sequenceDiagram\n    autonumber\n    participant C as Consumer login page\n    participant L as Login service\n    participant DB as MySQL\u003Cbr\u002F>(login_record)\n    participant A as Admin detail page\n    participant D as Customer detail service\n    participant G as GeoIpService\u003Cbr\u002F>(in-memory mmdb)\n\n    Note over G: Loads GeoLite2-Country.mmdb into memory at startup\n\n    rect rgb(235, 244, 255)\n    Note over C,DB: ① Capture the IP at login\n    C->>L: POST \u002Fauth\u002Flogin\n    L->>L: Take the real IP from X-Forwarded-For\n    L->>DB: Write login_ip (refreshed on every login)\n    L-->>C: token\n    end\n\n    rect rgb(255, 246, 232)\n    Note over A,G: ② Resolve the country in real time on detail\n    A->>D: POST \u002Fadmin\u002Fcustomer\u002Fdetail\n    D->>DB: Query the user's latest login_ip\n    D->>G: resolveCountryIsoCode(ip)\n    G-->>D: \"US\" (private \u002F unavailable → null)\n    D-->>A: country: \"US\"\n    A->>A: Intl.DisplayNames → \"美国 \u002F United States\"\n    end\n","mermaid",[17,322,323,331,337,343,349,355,361,367,373,380,386,391,397,403,409,415,421,427,433,438,444,450,456,462,468,474,480,486],{"__ignoreMap":189},[324,325,328],"span",{"class":326,"line":327},"line",1,[324,329,330],{},"sequenceDiagram\n",[324,332,334],{"class":326,"line":333},2,[324,335,336],{},"    autonumber\n",[324,338,340],{"class":326,"line":339},3,[324,341,342],{},"    participant C as Consumer login page\n",[324,344,346],{"class":326,"line":345},4,[324,347,348],{},"    participant L as Login service\n",[324,350,352],{"class":326,"line":351},5,[324,353,354],{},"    participant DB as MySQL\u003Cbr\u002F>(login_record)\n",[324,356,358],{"class":326,"line":357},6,[324,359,360],{},"    participant A as Admin detail page\n",[324,362,364],{"class":326,"line":363},7,[324,365,366],{},"    participant D as Customer detail service\n",[324,368,370],{"class":326,"line":369},8,[324,371,372],{},"    participant G as GeoIpService\u003Cbr\u002F>(in-memory mmdb)\n",[324,374,376],{"class":326,"line":375},9,[324,377,379],{"emptyLinePlaceholder":378},true,"\n",[324,381,383],{"class":326,"line":382},10,[324,384,385],{},"    Note over G: Loads GeoLite2-Country.mmdb into memory at startup\n",[324,387,389],{"class":326,"line":388},11,[324,390,379],{"emptyLinePlaceholder":378},[324,392,394],{"class":326,"line":393},12,[324,395,396],{},"    rect rgb(235, 244, 255)\n",[324,398,400],{"class":326,"line":399},13,[324,401,402],{},"    Note over C,DB: ① Capture the IP at login\n",[324,404,406],{"class":326,"line":405},14,[324,407,408],{},"    C->>L: POST \u002Fauth\u002Flogin\n",[324,410,412],{"class":326,"line":411},15,[324,413,414],{},"    L->>L: Take the real IP from X-Forwarded-For\n",[324,416,418],{"class":326,"line":417},16,[324,419,420],{},"    L->>DB: Write login_ip (refreshed on every login)\n",[324,422,424],{"class":326,"line":423},17,[324,425,426],{},"    L-->>C: token\n",[324,428,430],{"class":326,"line":429},18,[324,431,432],{},"    end\n",[324,434,436],{"class":326,"line":435},19,[324,437,379],{"emptyLinePlaceholder":378},[324,439,441],{"class":326,"line":440},20,[324,442,443],{},"    rect rgb(255, 246, 232)\n",[324,445,447],{"class":326,"line":446},21,[324,448,449],{},"    Note over A,G: ② Resolve the country in real time on detail\n",[324,451,453],{"class":326,"line":452},22,[324,454,455],{},"    A->>D: POST \u002Fadmin\u002Fcustomer\u002Fdetail\n",[324,457,459],{"class":326,"line":458},23,[324,460,461],{},"    D->>DB: Query the user's latest login_ip\n",[324,463,465],{"class":326,"line":464},24,[324,466,467],{},"    D->>G: resolveCountryIsoCode(ip)\n",[324,469,471],{"class":326,"line":470},25,[324,472,473],{},"    G-->>D: \"US\" (private \u002F unavailable → null)\n",[324,475,477],{"class":326,"line":476},26,[324,478,479],{},"    D-->>A: country: \"US\"\n",[324,481,483],{"class":326,"line":482},27,[324,484,485],{},"    A->>A: Intl.DisplayNames → \"美国 \u002F United States\"\n",[324,487,489],{"class":326,"line":488},28,[324,490,432],{},[13,492,493],{},"A few design points worth mentioning:",[13,495,496],{},[39,497,498],{},"1. The backend returns only the ISO code; the country name is left to the browser",[13,500,501,502,505],{},"The backend returns ",[17,503,504],{},"\"US\""," rather than \"United States\", and on the frontend one line of native API handles bilingual display for 200+ countries:",[183,507,511],{"className":508,"code":509,"language":510,"meta":189,"style":189},"language-ts shiki shiki-themes github-light github-dark github-dark","new Intl.DisplayNames([locale], { type: \"region\" }).of(\"US\");\n\u002F\u002F zh → \"美国\", en → \"United States\"\n","ts",[17,512,513,548],{"__ignoreMap":189},[324,514,515,519,523,527,530,534,537,540,543,545],{"class":326,"line":327},[324,516,518],{"class":517},"so5gQ","new",[324,520,522],{"class":521},"slsVL"," Intl.",[324,524,526],{"class":525},"shcOC","DisplayNames",[324,528,529],{"class":521},"([locale], { type: ",[324,531,533],{"class":532},"sfrk1","\"region\"",[324,535,536],{"class":521}," }).",[324,538,539],{"class":525},"of",[324,541,542],{"class":521},"(",[324,544,504],{"class":532},[324,546,547],{"class":521},");\n",[324,549,550],{"class":326,"line":333},[324,551,553],{"class":552},"sCsY4","\u002F\u002F zh → \"美国\", en → \"United States\"\n",[13,555,556,559],{},[39,557,558],{},"Zero i18n entries."," If the backend returned country names, I would either have to maintain a multilingual country table or push language negotiation into the API. Both are unnecessary complexity.",[13,561,562],{},[39,563,564],{},"2. Private IPs deliberately return null",[183,566,570],{"className":567,"code":568,"language":569,"meta":189,"style":189},"language-java shiki shiki-themes github-light github-dark github-dark","if (addr.isLoopbackAddress() || addr.isSiteLocalAddress()) {\n    return null;   \u002F\u002F no false country during local debugging \u002F intranet load testing\n}\n","java",[17,571,572,577,582],{"__ignoreMap":189},[324,573,574],{"class":326,"line":327},[324,575,576],{},"if (addr.isLoopbackAddress() || addr.isSiteLocalAddress()) {\n",[324,578,579],{"class":326,"line":333},[324,580,581],{},"    return null;   \u002F\u002F no false country during local debugging \u002F intranet load testing\n",[324,583,584],{"class":326,"line":339},[324,585,586],{},"}\n",[13,588,589],{},[39,590,591],{},"3. A database load failure only degrades; it does not block startup",[13,593,594],{},"When the mmdb is missing or corrupted, the service logs an error, returns null for every country, and starts up as usual. This \"gentleness\" nearly came back to bite me later (see pitfall ①).",[25,596,598],{"id":597},"_4-pitfalls-three-cases-of-works-fine-locally","4. Pitfalls: three cases of \"works fine locally\"",[71,600,602],{"id":601},"pitfall-the-pom-resource-whitelist-silently-swallowed-the-mmdb","Pitfall ①: the pom resource whitelist silently swallowed the mmdb",[13,604,605,608,609,612],{},[39,606,607],{},"Symptom",": after deployment the API returned ",[17,610,611],{},"\"country\": null",", always null. Locally, resolving 8.8.8.8 → US worked perfectly.",[13,614,615,616,619],{},"At the end of the investigation it turned out that resource packaging in the pom was in ",[39,617,618],{},"whitelist mode",":",[183,621,625],{"className":622,"code":623,"language":624,"meta":189,"style":189},"language-xml shiki shiki-themes github-light github-dark github-dark","\u003Cresource>\n    \u003Cdirectory>src\u002Fmain\u002Fresources\u003C\u002Fdirectory>\n    \u003Cincludes>\n        \u003Cinclude>**\u002F*.xml\u003C\u002Finclude>\n        \u003Cinclude>**\u002F*.yml\u003C\u002Finclude>\n        \u003Cinclude>**\u002F*.properties\u003C\u002Finclude>\n        \u003C!-- mmdb? Not here -->\n    \u003C\u002Fincludes>\n\u003C\u002Fresource>\n","xml",[17,626,627,632,637,642,647,652,657,662,667],{"__ignoreMap":189},[324,628,629],{"class":326,"line":327},[324,630,631],{},"\u003Cresource>\n",[324,633,634],{"class":326,"line":333},[324,635,636],{},"    \u003Cdirectory>src\u002Fmain\u002Fresources\u003C\u002Fdirectory>\n",[324,638,639],{"class":326,"line":339},[324,640,641],{},"    \u003Cincludes>\n",[324,643,644],{"class":326,"line":345},[324,645,646],{},"        \u003Cinclude>**\u002F*.xml\u003C\u002Finclude>\n",[324,648,649],{"class":326,"line":351},[324,650,651],{},"        \u003Cinclude>**\u002F*.yml\u003C\u002Finclude>\n",[324,653,654],{"class":326,"line":357},[324,655,656],{},"        \u003Cinclude>**\u002F*.properties\u003C\u002Finclude>\n",[324,658,659],{"class":326,"line":363},[324,660,661],{},"        \u003C!-- mmdb? Not here -->\n",[324,663,664],{"class":326,"line":369},[324,665,666],{},"    \u003C\u002Fincludes>\n",[324,668,669],{"class":326,"line":375},[324,670,671],{},"\u003C\u002Fresource>\n",[13,673,674,675,678],{},"The mmdb had never made it into the jar. And the \"only degrade on load failure\" fault tolerance made this failure ",[39,676,677],{},"completely silent",": the service was healthy, the API returned 200, and country was simply always null. Adding one include line fixed it.",[10,680,681],{},[13,682,683],{},"Lesson: when you build graceful degradation into a feature, also think about \"how will I know it has degraded\". Silent degradation = a failure with a delayed fuse.",[71,685,687],{"id":686},"pitfall-a-wildcard-in-a-javadoc-blew-up-the-build","Pitfall ②: a wildcard in a javadoc blew up the build",[13,689,690,691,694],{},"After fixing pitfall ①, I jotted down a note in a javadoc along the lines of \"the pom whitelist must include ",[17,692,693],{},"**\u002F*.mmdb","\", and compilation failed immediately:",[183,696,699],{"className":697,"code":698,"language":188,"meta":189},[186],"illegal character: '）'\nclass, interface, or enum expected\n",[17,700,698],{"__ignoreMap":189},[13,702,703,704,706,707,710,711,714],{},"It took a long stare to see it: ",[17,705,693],{}," contains ",[17,708,709],{},"*\u002F",", ",[39,712,713],{},"the terminator of a block comment",". The comment was cut in half right there, and the rest of the sentence (written in Chinese, full-width punctuation included) became illegal characters. I changed it to a plain-text description, \"the mmdb suffix\", and moved on.",[71,716,718],{"id":717},"pitfall-always-null-in-the-test-environment-because-you-are-on-the-intranet","Pitfall ③: always null in the test environment, because you are on the intranet",[13,720,721,722,724,725,247],{},"After logging in again, ",[17,723,19],{}," finally had a value, but country was still null. A look at the database: ",[17,726,727],{},"login_ip = 10.x.x.x",[13,729,730,731,734],{},"Traffic from the office network to the test environment goes over an internal path. The public IP is lost midway, and what gets written is the address of some NAT hop in between, which is then correctly intercepted by the \"no false country for private IPs\" logic I wrote myself. ",[39,732,733],{},"Not a bug, but a property of the path",": from the office intranet, country is always empty in the test environment. To see the real behavior, access it from a phone on mobile data, or simply change the IP in the database to simulate it.",[25,736,738],{"id":737},"_5-improving-the-design-a-scheduled-job-that-swaps-the-brain-every-week-for-the-offline-database","5. Improving the design: a scheduled job that \"swaps the brain every week\" for the offline database",[71,740,742],{"id":741},"why-this-is-a-must","Why this is a must",[13,744,745,746,749],{},"The biggest weakness of an offline database: ",[39,747,748],{},"it is a snapshot",". Which country an IP range belongs to keeps changing as carriers buy and sell ranges. MaxMind updates the database twice a week, while the file bundled into the jar is frozen at the moment of the build. Without an update mechanism:",[216,751,752,759],{},[36,753,754,755,758],{},"Accuracy ",[39,756,757],{},"degrades slowly"," over time, and with no errors at all, so you will not notice",[36,760,761],{},"The only way to replace the database is to ship a release, which ties \"swap a data file\" to \"change the code\"",[71,763,765],{"id":764},"how-often-to-update-weekly-but-take-a-look-every-day","How often to update: weekly, but take a look every day",[13,767,768,769,772],{},"Country-level data changes by less than a few tenths of a percent per month, so in terms of accuracy a monthly update would be enough. The real reason I settled on ",[39,770,771],{},"weekly"," is operational:",[10,774,775],{},[13,776,777,780],{},[39,778,779],{},"The more frequent the updates, the sooner a silent failure like \"the download path quietly broke\" gets exposed."," (The lesson from pitfall ① was still fresh.)",[13,782,783,784,247],{},"The implementation uses a small trick: ",[39,785,786],{},"cron fires every day, but only actually downloads once 7 days have passed",[183,788,790],{"className":318,"code":789,"language":320,"meta":189,"style":189},"flowchart TD\n    A[\"Triggered daily at 4:00\"] --> B{\"enabled?\"}\n    B -- No --> Z1[\"Return immediately\"]\n    B -- Yes --> C{\"External mmdb\u003Cbr\u002F>last written ≥ 7 days ago?\"}\n    C -- \"No (6 days a week)\" --> Z2[\"Skip, cost ≈ reading one file attribute\"]\n    C -- \"Yes \u002F file missing\" --> D[\"Fetch the new database from the data source into a temp file\u003Cbr\u002F>(~8.4MB)\"]\n    D --> E[\"Atomically replace the external file\u003Cbr\u002F>ATOMIC_MOVE, fall back to a plain move on failure\"]\n    E --> F{\"reload validation:\u003Cbr\u002F>① Country-type database?\u003Cbr\u002F>② 8.8.8.8 → US?\"}\n    F -- Pass --> G[\"In-memory reference switches to the new database\u003Cbr\u002F>old one closed, takes effect hot ✅\"]\n    F -- Fail --> H[\"Keep the old database in memory\u003Cbr\u002F>error log\"]\n    D -. Download fails .-> I[\"error log, keep the old database\"]\n    I --> J[\"Automatic retry at 4:00 the next day\u003Cbr\u002F>(file is still 'older than 7 days')\"]\n    H --> J\n",[17,791,792,797,802,807,812,817,822,827,832,837,842,847,852],{"__ignoreMap":189},[324,793,794],{"class":326,"line":327},[324,795,796],{},"flowchart TD\n",[324,798,799],{"class":326,"line":333},[324,800,801],{},"    A[\"Triggered daily at 4:00\"] --> B{\"enabled?\"}\n",[324,803,804],{"class":326,"line":339},[324,805,806],{},"    B -- No --> Z1[\"Return immediately\"]\n",[324,808,809],{"class":326,"line":345},[324,810,811],{},"    B -- Yes --> C{\"External mmdb\u003Cbr\u002F>last written ≥ 7 days ago?\"}\n",[324,813,814],{"class":326,"line":351},[324,815,816],{},"    C -- \"No (6 days a week)\" --> Z2[\"Skip, cost ≈ reading one file attribute\"]\n",[324,818,819],{"class":326,"line":357},[324,820,821],{},"    C -- \"Yes \u002F file missing\" --> D[\"Fetch the new database from the data source into a temp file\u003Cbr\u002F>(~8.4MB)\"]\n",[324,823,824],{"class":326,"line":363},[324,825,826],{},"    D --> E[\"Atomically replace the external file\u003Cbr\u002F>ATOMIC_MOVE, fall back to a plain move on failure\"]\n",[324,828,829],{"class":326,"line":369},[324,830,831],{},"    E --> F{\"reload validation:\u003Cbr\u002F>① Country-type database?\u003Cbr\u002F>② 8.8.8.8 → US?\"}\n",[324,833,834],{"class":326,"line":375},[324,835,836],{},"    F -- Pass --> G[\"In-memory reference switches to the new database\u003Cbr\u002F>old one closed, takes effect hot ✅\"]\n",[324,838,839],{"class":326,"line":382},[324,840,841],{},"    F -- Fail --> H[\"Keep the old database in memory\u003Cbr\u002F>error log\"]\n",[324,843,844],{"class":326,"line":388},[324,845,846],{},"    D -. Download fails .-> I[\"error log, keep the old database\"]\n",[324,848,849],{"class":326,"line":393},[324,850,851],{},"    I --> J[\"Automatic retry at 4:00 the next day\u003Cbr\u002F>(file is still 'older than 7 days')\"]\n",[324,853,854],{"class":326,"line":399},[324,855,856],{},"    H --> J\n",[13,858,859,860,863,864,867],{},"Why not simply ",[17,861,862],{},"cron = every 7 days","? Because ",[39,865,866],{},"checking daily + downloading only when due = a free retry mechanism",". Downloads can fail, so there has to be a retry, and here, if a download fails one day, it is naturally made up the next, without writing a single line of retry code.",[71,869,871],{"id":870},"three-engineering-details-of-the-hot-reload","Three engineering details of the hot reload",[13,873,874],{},[39,875,876],{},"1. Double validation: no pass, no swap",[13,878,879,880,883,884,887],{},"A new database is only allowed into memory if it is both \"a Country-type database\" and \"resolves the sample IP ",[17,881,882],{},"8.8.8.8"," to ",[17,885,886],{},"US","\". Downloaded half of a corrupted file? Validation fails and the old database stays in service.",[13,889,890],{},[39,891,892,893,896],{},"2. A ",[17,894,895],{},"volatile"," reference + atomic swap",[183,898,900],{"className":567,"code":899,"language":569,"meta":189,"style":189},"private volatile DatabaseReader reader;\n\npublic synchronized boolean reload(File file) {\n    DatabaseReader candidate = build(file);\n    if (!isValid(candidate)) { candidate.close(); return false; }\n    DatabaseReader old = reader;\n    reader = candidate;      \u002F\u002F swap the reference; immediately visible to query threads\n    old.close();             \u002F\u002F an in-flight query hitting the closed old database → falls into catch and returns null, unnoticed\n    return true;\n}\n",[17,901,902,907,911,916,921,926,931,936,941,946],{"__ignoreMap":189},[324,903,904],{"class":326,"line":327},[324,905,906],{},"private volatile DatabaseReader reader;\n",[324,908,909],{"class":326,"line":333},[324,910,379],{"emptyLinePlaceholder":378},[324,912,913],{"class":326,"line":339},[324,914,915],{},"public synchronized boolean reload(File file) {\n",[324,917,918],{"class":326,"line":345},[324,919,920],{},"    DatabaseReader candidate = build(file);\n",[324,922,923],{"class":326,"line":351},[324,924,925],{},"    if (!isValid(candidate)) { candidate.close(); return false; }\n",[324,927,928],{"class":326,"line":357},[324,929,930],{},"    DatabaseReader old = reader;\n",[324,932,933],{"class":326,"line":363},[324,934,935],{},"    reader = candidate;      \u002F\u002F swap the reference; immediately visible to query threads\n",[324,937,938],{"class":326,"line":369},[324,939,940],{},"    old.close();             \u002F\u002F an in-flight query hitting the closed old database → falls into catch and returns null, unnoticed\n",[324,942,943],{"class":326,"line":375},[324,944,945],{},"    return true;\n",[324,947,948],{"class":326,"line":382},[324,949,586],{},[13,951,952],{},[39,953,954,955,958],{},"3. ",[17,956,957],{},"FileMode.MEMORY"," to avoid file locks",[13,960,961,962,965,966,968],{},"DatabaseReader defaults to MEMORY_MAPPED (memory mapping), and on Windows a mapped file ",[39,963,964],{},"cannot be replaced",", so hot reload in the development environment would simply fall over. Switching to ",[17,967,957],{}," reads the whole file onto the heap (it is only 8MB anyway), holds no handle on the file, and lets it be replaced freely.",[13,970,971,972,247],{},"This goes together with the reworked loading priority: ",[39,973,974],{},"external file first, the copy bundled in the jar as the fallback",[216,976,977,980,986],{},[36,978,979],{},"First deployment: the external directory is empty → use the database bundled in the jar → the job downloads and writes the file at 4:00 that day",[36,981,982,983],{},"Afterwards: always use the latest external database, and ",[39,984,985],{},"releases never have to worry about swapping the mmdb again",[36,987,988],{},"External file corrupted: a load failure at startup automatically falls back to the bundled database, so there is always a safety net",[25,990,992],{"id":991},"_6-honest-boundaries-what-this-approach-cannot-do","6. Honest boundaries: what this approach cannot do",[76,994,995,1005],{},[79,996,997],{},[82,998,999,1002],{},[85,1000,1001],{},"Limitation",[85,1003,1004],{},"Details",[98,1006,1007,1015,1027,1035,1043],{},[82,1008,1009,1012],{},[103,1010,1011],{},"Country ≠ where the user really is",[103,1013,1014],{},"With a VPN\u002Fproxy you see the exit country; anycast IPs (such as 1.1.1.1) have no attribution and return null",[82,1016,1017,1020],{},[103,1018,1019],{},"The head of the XFF chain can be forged",[103,1021,1022,1023,1026],{},"Fine for display, but it must ",[39,1024,1025],{},"never"," be used for risk control, compliance, or purchase-restriction decisions",[82,1028,1029,1032],{},[103,1030,1031],{},"It only represents \"the most recent login\"",[103,1033,1034],{},"When the user travels or switches nodes, the country jumps with them; it is neither the place of registration nor the place of residence",[82,1036,1037,1040],{},[103,1038,1039],{},"Cannot filter by country in SQL",[103,1041,1042],{},"The country is not persisted. The day a PM asks to \"filter customers by country\" or wants a country distribution report is the signal to switch to the \"resolve at login and persist\" approach (GeoIpService can be reused as is, so the migration cost is low)",[82,1044,1045,1048],{},[103,1046,1047],{},"Gap for existing users",[103,1049,1050],{},"country is empty for existing users until their next login; channels where the real IP is unavailable (such as messages forwarded by a bot) stay empty forever",[25,1052,1054],{"id":1053},"_7-takeaways","7. Takeaways",[33,1056,1057,1063,1069,1078,1084,1090],{},[36,1058,1059,1062],{},[39,1060,1061],{},"Probe before you choose; do not guess the architecture from documentation."," Two DNS queries + one curl ruled out the most tempting option A in five minutes, far faster than discussing it in a meeting",[36,1064,1065,1068],{},[39,1066,1067],{},"If \"an existing column + compute at query time\" solves it, do not rush into DDL."," Data that is never persisted never needs to be cleaned up",[36,1070,1071,1077],{},[39,1072,1073,1074,247],{},"Leave display mappings like country names to ",[17,1075,1076],{},"Intl.DisplayNames"," Browsers natively ship entries for 200+ countries in every language",[36,1079,1080,1083],{},[39,1081,1082],{},"Graceful degradation must come with \"how will I know it has degraded\"."," Otherwise you get the illusion of health from pitfall ①",[36,1085,1086,1089],{},[39,1087,1088],{},"Offline data = a snapshot, and a snapshot needs a mechanism to keep it fresh."," \"Check daily + download when due\" gets retries for free in the dumbest possible way",[36,1091,1092,1093,1095,1096,1098],{},"Do not let ",[17,1094,709],{}," appear in a javadoc, even when it is growing inside the wildcard ",[17,1097,693],{}," :)",[1100,1101,1102],"style",{},"html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .so5gQ, html code.shiki .so5gQ{--shiki-light:#D73A49;--shiki-default:#F97583;--shiki-dark:#F97583}html pre.shiki code .slsVL, html code.shiki .slsVL{--shiki-light:#24292E;--shiki-default:#E1E4E8;--shiki-dark:#E1E4E8}html pre.shiki code .shcOC, html code.shiki .shcOC{--shiki-light:#6F42C1;--shiki-default:#B392F0;--shiki-dark:#B392F0}html pre.shiki code .sfrk1, html code.shiki .sfrk1{--shiki-light:#032F62;--shiki-default:#9ECBFF;--shiki-dark:#9ECBFF}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}",{"title":189,"searchDepth":333,"depth":333,"links":1104},[1105,1106,1112,1113,1118,1123,1124],{"id":27,"depth":333,"text":28},{"id":68,"depth":333,"text":69,"children":1107},[1108,1109,1110,1111],{"id":73,"depth":339,"text":74},{"id":177,"depth":339,"text":178},{"id":210,"depth":339,"text":211},{"id":233,"depth":339,"text":234},{"id":307,"depth":333,"text":308},{"id":597,"depth":333,"text":598,"children":1114},[1115,1116,1117],{"id":601,"depth":339,"text":602},{"id":686,"depth":339,"text":687},{"id":717,"depth":339,"text":718},{"id":737,"depth":333,"text":738,"children":1119},[1120,1121,1122],{"id":741,"depth":339,"text":742},{"id":764,"depth":339,"text":765},{"id":870,"depth":339,"text":871},{"id":991,"depth":333,"text":992},{"id":1053,"depth":333,"text":1054},"2026-07-22","The customer detail page needed to show a user's country. I resolve the login IP locally with the GeoLite2 offline database, with zero DDL and zero outbound calls, plus a weekly hot-reload job to keep the data fresh.","md",null,"\u002Farticles\u002Fgeoip-user-country.svg",{},"\u002Farticles\u002Fgeoip-user-country","9",{"title":5,"description":1126},{"loc":1131},"articles\u002Fgeoip-user-country",[1137,1138],"Full-Stack","Backend","LawAdj75AECq5aCoChBsVixPronL38oPV7uXmXST1gI",1795761651584]