It uses very complex hand optimized SQL queries to do everything in a single database query. The database is also structured in a way to support this.
The result: each request overall only takes a few milliseconds for the hardest part, the rest of the optimization is a game of caching.