RSS

Building a simple IP geolocation service

One of the really nice features of Intercom is that you can see the location and local time of your app’s users. We use their IP address to determine roughly where they are. To do this we use the free MaxMind dataset and accompanying geoip gem. From our experience the free dataset provides excellent results down to city level.

In order to keep our API lean, we do as much work as possible out of the request/response cycle. We use resque to queue and perform these tasks. Rather than storing the MaxMind dataset (at 27 MB) in memory for each resque worker process, I decided to build a standalone Sinatra app whose sole purpose is to serve a JSON formatted geocode result. This is not a new idea, Geoffry Grosenbach did something similar a while ago, but I wanted to build my own app that could be deployed straight to heroku (and also make some tweaks of my own).

The app itself resides on heroku and the source is on github, it includes the MaxMind data set, and is ready to deploy. It’s very fast, typical response times are under three milliseconds. It sets ‘Cache-Control’ headers so that (if deployed to heroku) all but the first request for a particular IP will be served out of the Varnish cache.

It can also be used to serve JSONP to web browsers, just make a JSONP call to http://latlng.heroku.com/locateme.json and it will return info about your location.