SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Geohash
  • Quad Trees
  • R-Trees
  • S2 and H3
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Geospatial Structures

R-Trees

Group nearby shapes inside boxes, and boxes inside bigger boxes, to search maps fast.

⏱ 13 min readAdvancedHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An R-tree is a tree for storing shapes and areas on a map. It puts nearby shapes inside a box, puts nearby boxes inside a bigger box, and so on up to one box that covers everything.

  • Each box is the smallest rectangle that fits everything below it. It is called a bounding box (or MBR).
  • To search an area, you skip every box that does not touch it. Whole branches of the tree are ignored.
  • Unlike a quad tree, the boxes can overlap and are sized by the data. This makes R-trees good for roads, buildings and regions, and good for storing on disk.

02Concept: What is it?

Points are easy: a point is in a square or it is not. Real map data has shapes: a lake, a road, a building, a delivery zone. A shape can cross many squares of a grid, and then you have to store it many times. The R-tree avoids this by giving every shape one place in the tree.

Every shape is first wrapped in its bounding box, the smallest rectangle that contains it. Boxes that are near each other are grouped, and the group gets its own bigger bounding box. Groups of groups get a still bigger box, until one root box covers all. The tree is balanced: all leaves are at the same depth, like a B-tree.

Boxes inside boxes
🔷Shapeslakes, roads, buildings
→↓wrap in boxes
📦Leaf boxesa few shapes each
→↓group nearby boxes
🗃️Bigger boxesboxes of boxes
→↓until one
🌍Root boxcovers everything
Each level is a bounding box around the boxes below it.

A search says: “I want everything touching this window.” Start at the root. For every child box that touches the window, go inside. For every child box that does not, skip it and everything beneath it. At a leaf, check the real shapes.

🧠Boxes may overlap
Two sibling boxes can cover some of the same ground. A search that lands in the overlap must go into both. The less the boxes overlap, the faster the tree.

03Real-Life Example

🍵The Warehouse of Labelled Boxes
A warehouse stores thousands of odd-shaped items. Items that belong on the same part of a map are put in a small box, with a label saying which part of the map it covers. Small boxes sit inside bigger crates, crates sit on pallets, and pallets sit in an aisle. To find everything in one town, you look at the aisle labels, then the pallet labels, then the crates. You never open the ones whose label is about another place. If you packed the boxes carelessly (a far-away item next to a nearby one) the labels become huge and useless, and you have to open everything.
Warehouse
R-tree
An odd-shaped item
A shape (road, lake, building)
A small box with a label of its area
A leaf node with a bounding box
A crate holding several boxes
An inner node holding child boxes
Labels read before opening anything
Comparing the search window with bounding boxes
Packing nearby items together
Grouping by place (the tree-building rule)
Packing carelessly, huge labels
Heavy overlap, so the search visits many nodes
Searching an R-tree
🔍Window
→↓touches?
🌍Root
→↓only touching children
📦Some leaf boxesmost skipped
→↓check real shapes
✅Results

04Why Do We Need It?

🔷Handles shapes
Roads, buildings and regions are stored once, not cut into many cells.
⚡Fast window search
Boxes that miss the window are skipped with all the data below them.
💽Built for disk
Each node fits a disk page and the tree stays balanced, like a B-tree.
🔄Dynamic
Shapes can be inserted and deleted without rebuilding the whole tree.
🎯Nearest neighbour
Visit boxes in order of distance, and stop when nothing closer can exist.
📐Any number of dimensions
The same idea works with 3D boxes or other number ranges.
An R-tree wraps shapes in nested boxes, so a map query opens only the few boxes that touch the area you ask about.

05Where Do We Use It?

🗺️GIS databases
PostGIS (PostgreSQL) and SpatiaLite index shapes with R-tree-style indexes.
🗄️SQLite and MySQL
SQLite has an R-tree module, and MySQL uses R-tree indexes for spatial columns.
🏠Real estate and zones
Find parcels or delivery zones that touch a map window.
🛣️Roads and routing
Find road segments near a GPS point.
🎮Game worlds
Look up objects with a size, not only a single point.
📊Range data
Any data with ranges in several dimensions, such as price × time.

06Types / Parts / How It Works

The pieces of an R-tree

Structure
🌍Rootbox covers all
↓
🗃️Inner A
🗃️Inner B
↓
📦Leaf 1
📦Leaf 2
📦Leaf 3
📦Leaf 4
↓
🔷Shapesstored with their boxes
Root Inner nodes Leaves Data
Inner nodes hold boxes of children. Leaf nodes hold the bounding boxes of the real shapes.

Variants

VariantIdeaGood and bad
Classic R-treeInsert into the box that grows least; split a full node into twoSimple, but overlap can grow
R*-treeSmarter choice and split rules, plus re-inserting entries to reduce overlapFaster queries, slower inserts
R+-treeBoxes at one level never overlap, but a shape may be stored in several leavesSearches follow one path, at the cost of duplicates
Packed / bulk-loadedSort the data by place and build the tree from the bottomBest for data that rarely changes (the visualizer builds this way)

Why overlap matters

Well-packed boxes (little overlap)few nodes visited per search
Careless boxes (lots of overlap)many nodes visited per search
VisualizerR-tree: nested boxes and a search windowBuild with nearby shapes together, then with arrival order, and compare box overlap and the nodes visited. Move and resize the green window. Change how many entries fit in one box.
How are shapes grouped into boxes?
Draw

Solid outlines = bottom boxes (cyan). Dashed outlines = boxes of boxes. Bright = visited by the search, faint = skipped. Green shapes = found.

Tree height
3
17 nodes
Nodes visited
5
of 17
Shapes checked
12
of 40 (scan checks all)
Box overlap
3%
bottom boxes
Found
5
matches a full scan
Nearby shapes share a box, so whole boxes that miss the search window are skipped. Only 12 of 40 shapes were checked.

A simplified, bulk-built R-tree: shapes are packed into boxes, and boxes into bigger boxes, level by level. Real R-trees also support inserts and splits, but the search works the same way: skip every box that does not touch the window. Shapes are made with a seeded generator, so the data never changes between visits.

07How to Use It / Steps / Implementation

Using an R-tree

  1. 1
    Wrap each shape in a bounding box
    Store the smallest rectangle that contains the shape. This is what the tree compares.
  2. 2
    Insert
    Go down, always choosing the child box that has to grow the least to include the new box. Add it to a leaf.
  3. 3
    Split when a node is full
    A full node splits into two nodes, and the parent gets one more entry. Splits can go up to the root, which then makes the tree one level taller.
  4. 4
    Search a window
    From the root, go into every child whose box touches the window. At the leaves, collect the shapes whose boxes touch it.
  5. 5
    Refine
    A bounding box is bigger than the shape. Run an exact check on the real shape before returning it.
  6. 6
    Bulk-load for static data
    If you have all the data up front, sort it by place and pack it. The tree has less overlap and is faster than one built by inserts.
  7. 7
    Create the index in the database
    In SQL, a spatial index (for example a GiST index in PostGIS) builds and maintains the tree for you.
💡Two steps: filter, then refine
The tree gives you candidates whose bounding boxes touch the window. Then an exact geometry test removes false matches. Databases do both for you.
⚠️Bad packing hurts
If shapes are inserted in a random order, boxes can overlap a lot and the search slows down. For mostly-static data, bulk-load.

08Key Terms to Know

TermMeaning in easy words
Bounding box / MBRThe smallest rectangle (minimum bounding rectangle) that holds a shape or a group of boxes
LeafA node that holds the boxes of real shapes
Inner nodeA node that holds the boxes of its child nodes
OverlapArea covered by two sibling boxes at once; it forces a search to follow both
Fan-outHow many entries one node holds (the 'entries per box' in the visualizer)
BalancedAll leaves are at the same depth
SplitDividing a full node into two
Bulk loadingBuilding a tree from sorted data in one pass, bottom up
Window queryFind everything touching a rectangle
Nearest neighbourFind the shape closest to a point
Filter and refineCheap box test first, exact shape test second

09Pros, Cons and Trade-offs

✅ Pros
  • Stores shapes naturally, each only once
  • Balanced and disk-friendly
  • Fast window and nearest searches
  • Supports inserts and deletes
  • Works in more than two dimensions
⚠️ Cons
  • Overlap can make searches visit many nodes
  • No guaranteed worst case for a search
  • Inserts and splits are harder than a B-tree's
  • Quality depends on insert order and split rules
  • Bounding boxes are only a rough filter

Trade-offs

ChoiceWe gainWe lose
Bigger nodes (high fan-out)A shorter tree and fewer disk readsMore boxes to compare inside each node
Smaller nodesTighter, more precise boxesA taller tree
Bulk-loaded treeLittle overlap, fast queriesNot made for many later changes
Built by insertsAlways up to dateMore overlap over time
R*-tree rulesBetter queriesSlower inserts
R-treeGood for shapes and disksMore complex than a quad tree or grid for plain points

10Common Problems and Mistakes

Common mistakes

  1. Skipping the exact test. A bounding box touching the window does not mean the shape does.
  2. Using it for simple points on a map. A geohash or quad tree may be simpler.
  3. Random insert order for big static data. Bulk-load instead for much less overlap.
  4. Long thin shapes. A diagonal road has a huge bounding box that is mostly empty, so it matches many windows. Split long shapes into pieces.
  5. Forgetting to update the index. Data and index must change together, or searches miss rows.
  6. Ignoring the spatial reference. Boxes in degrees and in metres are different things. Use the right coordinate system.

Things to watch

🕸️Growing overlap
After many updates, rebuild or re-pack the index.
📏Huge shapes
A country-sized shape touches every window. Consider splitting it.
🧭Nearest queries
Make sure the planner uses the index for ORDER BY distance.
🔒Concurrent writes
Splits touch several nodes, so locking is more complex than for a B-tree.

11Real-World Examples

🐘PostGIS
Spatial indexes in PostgreSQL are R-tree style, built on the GiST index framework.
🐬MySQL spatial indexes
Spatial columns use R-tree indexes.
🪶SQLite R*Tree
A built-in module for range queries over boxes.
🗺️Mapping and GIS software
Libraries for map data commonly offer an R-tree for fast lookups.
🛣️Routing
Snap a GPS point to the closest road segment using an index of segment boxes.
🎮Collision lookups
Find objects whose bounding boxes touch a given area.
📝Note
Index types and defaults change with each version. Check the documentation of your database for the exact syntax and behaviour.
Mini case: which delivery zones cover this address?
🏠Addressa point
→↓window query
🌳R-treezone boxes
→↓3 candidates
📐Exact testpoint in polygon
→↓1 zone
🚚Zone 12
Zones are polygons. The index returns candidates, then an exact test confirms.

12Related Topics to Read Next

Quad Trees→

Splits space in a fixed way. Simpler, and good for points.

Geohash→

Turns places into strings that any index can store.

S2 and H3→

Cell systems for the whole Earth.

B-Trees and B+ Trees→

R-trees are balanced and page-based like these, but for boxes.

Indexing→

A spatial index is one more kind of index to avoid scanning.

Relational Databases→

PostGIS and MySQL offer R-tree style spatial indexes.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: a balanced tree of nested bounding boxes around shapes.
  • ✔Search: skip every box that misses the window, then check real shapes.
  • ✔Two steps: filter with boxes, refine with exact geometry.
  • ✔Overlap: the enemy. Less overlap means fewer nodes visited.
  • ✔Build: insert (box that grows least) with splits, or bulk-load for static data.
  • ✔Variants: R*-tree (better splits), R+-tree (no overlap, shapes duplicated).
  • ✔Used in: PostGIS, MySQL spatial indexes, SQLite R*Tree, GIS and routing.
  • ✔One line: “Pack shapes into boxes, boxes into bigger boxes, and open only the boxes that touch your question.”
← Previous
Quad Trees
Next →
S2 and H3