No External API, No DDL: How the "User Country" Field Grew Out of a Login IP
2026-07-22
|
9 mins to read
|
Share article
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
login_ipcolumn that had been sitting there for half a year without anyone writing to it.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".
1. Breaking down the requirement: it is really two problems
"Show the user's country on the detail page" splits into two things:
- Get the user's IP — when do we capture it, and where do we store it?
- Turn the IP into a country — what do we resolve it with?
The first one is easy to agree on: the IP at login time is the most representative (it is backed by an explicit user action), and the login record table login_record already had a login_ip column lying around. Whoever created the table clearly thought of it; the login flow just never wrote to it.
The second one is where the real decision-making happens.
2. Comparing the options: four roads, three ruled out by testing
The candidates
| Option | How it works | Pros | Fatal flaw |
|---|---|---|---|
| A. Ready-made header from the CDN/gateway | Cloudflare's CF-IPCountry, CloudFront's CloudFront-Viewer-Country; the backend just reads a header | Zero code, zero dependencies, reusable site-wide | You need to have a CDN in the first place |
| B. Online IP geolocation API | Call ip-api / ipinfo at login and persist the country | Least code, data is always current | External dependency (quota/latency/availability), needs DDL, user IPs leave your system for a third party |
| C. Local offline database, GeoLite2 | Bundle the mmdb file into the jar and query it in memory | No outbound calls, no quota, microsecond lookups, zero DDL | jar grows by 8MB; the data is a snapshot and goes stale |
| D. Local offline database, ip2region | Same as C, with the xdb format instead | Fully open source, can be committed to the repo | 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 |
Ruling out option A (a pleasant bit of DNS detective work)
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:
$ Resolve-DnsName api.example.com
→ no CNAME pointing to a CDN
$ curl -sI https://api.example.com/
→ no cf-ray, no via: cloudfront in the response headers
Conclusion: testing confirmed that there is 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.
A bonus finding along the way: only once you know exactly which hops are on the request path can you decide which part of
X-Forwarded-Forthe backend should trust. On our path, taking the real client IP from the head of the chain is reliable.
Why option B was ruled out
It is not that an online API cannot work; it is just a bad deal for this scenario:
- You must 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
- 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
- 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/month. It is enough today only because the volume is small today
The final choice: C (GeoLite2 mmdb) + resolve at query time
Besides the data source, there is an orthogonal decision: when to resolve.
| Timing | Pros | Cons |
|---|---|---|
| Resolve at login → persist the country | Zero resolution cost on the detail page; can filter/report by country in SQL | Needs DDL; after an mmdb upgrade the existing rows hold outdated conclusions |
| Resolve in real time at query time (✅) | Zero DDL; historical data is automatically recomputed when the database is replaced; the country is never persisted, so there is no dirty data | One extra table query per detail request; cannot filter by country in SQL |
Right now the only consumer is "display on the detail page", so I went with resolving at query time. 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.
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 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.
3. The design: two flows, decoupled by one column
The whole implementation is split by the single column login_record.login_ip into two flows that do not interfere with each other:
A few design points worth mentioning:
1. The backend returns only the ISO code; the country name is left to the browser
The backend returns "US" rather than "United States", and on the frontend one line of native API handles bilingual display for 200+ countries:
new Intl.DisplayNames([locale], { type: "region" }).of("US");
// zh → "美国", en → "United States"
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.
2. Private IPs deliberately return null
if (addr.isLoopbackAddress() || addr.isSiteLocalAddress()) {
return null; // no false country during local debugging / intranet load testing
}
3. A database load failure only degrades; it does not block startup
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 ①).
4. Pitfalls: three cases of "works fine locally"
Pitfall ①: the pom resource whitelist silently swallowed the mmdb
Symptom: after deployment the API returned "country": null, always null. Locally, resolving 8.8.8.8 → US worked perfectly.
At the end of the investigation it turned out that resource packaging in the pom was in whitelist mode:
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.yml</include>
<include>**/*.properties</include>
<!-- mmdb? Not here -->
</includes>
</resource>
The mmdb had never made it into the jar. And the "only degrade on load failure" fault tolerance made this failure completely silent: the service was healthy, the API returned 200, and country was simply always null. Adding one include line fixed it.
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.
Pitfall ②: a wildcard in a javadoc blew up the build
After fixing pitfall ①, I jotted down a note in a javadoc along the lines of "the pom whitelist must include **/*.mmdb", and compilation failed immediately:
illegal character: ')'
class, interface, or enum expected
It took a long stare to see it: **/*.mmdb contains */, 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.
Pitfall ③: always null in the test environment, because you are on the intranet
After logging in again, login_ip finally had a value, but country was still null. A look at the database: login_ip = 10.x.x.x.
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. 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.
5. Improving the design: a scheduled job that "swaps the brain every week" for the offline database
Why this is a must
The biggest weakness of an offline database: 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:
- Accuracy degrades slowly over time, and with no errors at all, so you will not notice
- The only way to replace the database is to ship a release, which ties "swap a data file" to "change the code"
How often to update: weekly, but take a look every day
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 weekly is operational:
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.)
The implementation uses a small trick: cron fires every day, but only actually downloads once 7 days have passed.
Why not simply cron = every 7 days? Because 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.
Three engineering details of the hot reload
1. Double validation: no pass, no swap
A new database is only allowed into memory if it is both "a Country-type database" and "resolves the sample IP 8.8.8.8 to US". Downloaded half of a corrupted file? Validation fails and the old database stays in service.
2. A volatile reference + atomic swap
private volatile DatabaseReader reader;
public synchronized boolean reload(File file) {
DatabaseReader candidate = build(file);
if (!isValid(candidate)) { candidate.close(); return false; }
DatabaseReader old = reader;
reader = candidate; // swap the reference; immediately visible to query threads
old.close(); // an in-flight query hitting the closed old database → falls into catch and returns null, unnoticed
return true;
}
3. FileMode.MEMORY to avoid file locks
DatabaseReader defaults to MEMORY_MAPPED (memory mapping), and on Windows a mapped file cannot be replaced, so hot reload in the development environment would simply fall over. Switching to FileMode.MEMORY reads the whole file onto the heap (it is only 8MB anyway), holds no handle on the file, and lets it be replaced freely.
This goes together with the reworked loading priority: external file first, the copy bundled in the jar as the fallback.
- 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
- Afterwards: always use the latest external database, and releases never have to worry about swapping the mmdb again
- External file corrupted: a load failure at startup automatically falls back to the bundled database, so there is always a safety net
6. Honest boundaries: what this approach cannot do
| Limitation | Details |
|---|---|
| Country ≠ where the user really is | With a VPN/proxy you see the exit country; anycast IPs (such as 1.1.1.1) have no attribution and return null |
| The head of the XFF chain can be forged | Fine for display, but it must never be used for risk control, compliance, or purchase-restriction decisions |
| It only represents "the most recent login" | When the user travels or switches nodes, the country jumps with them; it is neither the place of registration nor the place of residence |
| Cannot filter by country in SQL | 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) |
| Gap for existing users | 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 |
7. Takeaways
- 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
- 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
- Leave display mappings like country names to
Intl.DisplayNames. Browsers natively ship entries for 200+ countries in every language - Graceful degradation must come with "how will I know it has degraded". Otherwise you get the illusion of health from pitfall ①
- 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
- Do not let
*/appear in a javadoc, even when it is growing inside the wildcard**/*.mmdb:)