System Design Part 3 Storage basics

Indexes and B+Trees: From Disk Pages to Composite Indexes, Index-Defeating Queries, and Keyset Pagination

Bill.Lin 23 min read

System Design series Part 3-2 | Previous: SQL vs NoSQL | Next: B-Tree vs LSM-Tree | Series map

Scenario and problem

The “My orders” API in the member center sits on a purchase_order table with 50 million rows. Each row is about 200 bytes, so the data alone is about 10 GB. After launch, problems kept showing up:

  1. Fetching one member’s latest 20 orders takes 8 seconds
  2. An index on member_id made it faster, but “a member’s paid orders, sorted by time” is still slow
  3. The back office’s WHERE DATE(created_at) = '2026-11-11' stays slow no matter which index you add
  4. Customer support looks up members by phone number, and WHERE phone = 0912345678 scans the whole table every time
  5. To speed things up, someone added 12 indexes in one go; during the big sale, writes slowed down and replica lag shot up
  6. Fetching page 5,000 takes 3 seconds
Six slow queries on a 50-million-row order table1 / 6
Six slow queries on a 50-million-row order tableMemberOrder APIOrder tableOps & supportMemberOrder APIOrder tableMy ordersLatest 20Row-by-row scan, 8 sOrder APIOrder tablePaid + by timeFast lookup, slow sortOps & supportOrder APIOrder tableOrders on 11/11DATE(column)Index unusableOps & supportOrder APIOrder tableFind by phonephone = numberFull scan every timeOrder APIOrder tableBig-sale writes13 trees per insertMemberOrder APIOrder tablePage 5,000OFFSET 100,0003 s
  1. 8 s for the latest 20"My orders" fetches one member's latest 20 orders. The table has 50 million rows, about 10 GB, and there is no usable index, so the database can only scan it row by row.
  2. Still slow with an indexWith an index on member_id, finding the member is fast; but "paid, sorted by time" is still slow, because the index order does not match the order the query wants, so the rows need a separate sort.
  3. No index helpsThe back office queries one day's orders with DATE(created_at). The column is wrapped in a function while the index stores the raw values, so no index you add can be used.
  4. Look up a member by phonephone is a string column, but the query passes a number. When comparing a string with a number, MySQL converts every row's string to a number before comparing, so the whole table is scanned.
  5. 12 indexes at onceSomeone added 12 indexes to speed things up. Every insert has to change the primary key plus 12 trees, so writes slow down during the big sale and the replicas fall behind.
  6. Page 5,000 takes 3 sAt 20 rows per page, page 5,000 means OFFSET 100,000: the database first counts through 100,000 rows and throws them away, and the deeper the page, the slower it gets.

All six problems involve indexes, but each has a different cause. To tell them apart, you first need to know what an index looks like on disk.

The simplest approach and its limits

Without an index, the database can only do a full table scan: read all 50 million rows and check the condition on each one. The cost is proportional to the amount of data, so 10 times the data is 10 times slower; 10 such queries at once means 10 times the I/O.

If the data is sorted by some column, you can use binary search: log₂(50 million) ≈ 26 comparisons. But inserting into a sorted array is expensive, and the array can only be sorted one way. A binary search tree handles inserts too, but it is about 26 levels tall; if each level sits in a different place on disk, one query costs 26 random reads. Random reads from disk (even an SSD) are hundreds of times slower than memory, or worse, and 26 of them is too many.

What the database needs is a short, wide tree: each node is exactly one disk page, so one read gets you over a thousand branches. That is the B+Tree.

Core mechanism

B+Tree: a tree designed for disk pages

flowchart TD
    R["Root node (one 16 KB page)<br/>about 1,170 branches"] --> I1[Internal node]
    R --> I2[Internal node]
    R --> I3["…"]
    I1 --> L1["Leaf node: full rows for id 1–76"]
    I1 --> L2["Leaf node: id 77–152"]
    I2 --> L3["Leaf node: …"]
    L1 -. doubly linked list .-> L2
    L2 -. doubly linked list .-> L3
  • Each node is one page: 16 KB by default in InnoDB. Internal nodes store only “key + pointer to a child node”, so one page holds over a thousand branches
  • Data lives only in the leaf nodes, and the leaves are linked to each other in a list. A range query (BETWEEN, ORDER BY ... LIMIT) finds its starting point and then just reads along the list

How much data can one B+Tree hold? Assume the primary key is a BIGINT and each branch in an internal node takes about 14 bytes:

Calculation (java BPlusTreeCapacity.java)
java
public class BPlusTreeCapacity {

    static final int PAGE_BYTES = 16 * 1024;           // InnoDB default page size
    static final double LEAF_FILL = 15.0 / 16;         // with sequential inserts, leaf pages keep about 1/16 free

    public static void main(String[] args) {
        int internalEntryBytes = 8 + 6;                 // BIGINT primary key + pointer to the child node (estimate)
        long fanout = PAGE_BYTES / internalEntryBytes;
        System.out.printf("About %,d branches per internal page%n", fanout);

        for (int rowBytes : new int[] {200, 1000}) {
            long rowsPerLeaf = (long) (PAGE_BYTES * LEAF_FILL / rowBytes);
            System.out.printf("%n%,d bytes per row, about %d rows per leaf node%n", rowBytes, rowsPerLeaf);
            for (int height = 1; height <= 4; height++) {
                double rows = Math.pow(fanout, height - 1) * rowsPerLeaf;
                System.out.printf("  Height %d: up to about %,.0f rows%n", height, rows);
            }
        }
    }
}
text
About 1,170 branches per internal page

200 bytes per row, about 76 rows per leaf node
  Height 1: up to about 76 rows
  Height 2: up to about 88,920 rows
  Height 3: up to about 104,036,400 rows
  Height 4: up to about 121,722,588,000 rows

1,000 bytes per row, about 15 rows per leaf node
  Height 1: up to about 15 rows
  Height 2: up to about 17,550 rows
  Height 3: up to about 20,533,500 rows
  Height 4: up to about 24,024,195,000 rows

(This ignores overhead such as page headers; it is an order-of-magnitude estimate.)

Three levels hold about 100 million rows. And the root and internal nodes together are only a little over a thousand pages (about 20 MB), so they almost always stay in InnoDB’s buffer pool. A primary key lookup therefore usually reads only that last leaf node from disk, and often even the leaf is already in memory. That is the physical reason “primary key lookups are fast”.

The output also shows that the wider each row, the fewer rows the same tree height can hold. Moving large columns (long text, JSON) to another table makes the main table’s tree shorter and fits more rows on each page.

Clustered and secondary indexes

In InnoDB, the whole table is a B+Tree sorted by primary key (the clustered index), and its leaf nodes hold the full rows. Every other index (a secondary index) is a separate B+Tree whose leaf nodes hold “the indexed columns + the primary key value”, not the data itself:

flowchart LR
    Q["WHERE member_id = 42"] --> S["Secondary index (member_id)<br/>leaf: member_id, id"]
    S -- "gets id = 918273" --> P["Primary key index (clustered)<br/>leaf: full row"]
    P --> Row[The complete row]

So a query through a secondary index walks two trees: it finds the primary key in the secondary index, then goes back to the primary key index for the full row (often called “going back to the table”). If every column the query needs is in the secondary index, there is no trip back to the table. That is a covering index, and the Extra column of EXPLAIN shows Using index.

This structure leads to three important consequences:

  1. The wider the primary key, the bigger every index: every entry in every secondary index carries the primary key. A 36-character UUID string as the primary key adds 36 bytes to every entry in every index
  2. The primary key order is the physical order of the data: inserts with an increasing primary key always land at the far right of the tree, and pages fill up in order; random UUIDv4 values land anywhere in the tree, causing many page splits and random I/O. For generating “roughly increasing” IDs in a distributed system, see Distributed IDs
  3. A secondary index implicitly ends with the primary key: in InnoDB, INDEX (member_id, created_at) is effectively (member_id, created_at, id). Keyset pagination, later in this post, relies on exactly that

Composite indexes and the leftmost prefix

A composite index (member_id, status, created_at) is sorted like a phone book: by the first column, then by the second column when the first is equal, and so on. So only “contiguous columns starting from the leftmost one” can be used to locate a range.

Simulate this index with a TreeSet: 2,000 members with 100 orders each, 200,000 entries in total, and compare how many entries each condition has to scan:

Simulation (java LeftmostPrefixDemo.java)
java
import java.time.LocalDate;
import java.util.Comparator;
import java.util.NavigableSet;
import java.util.Random;
import java.util.TreeSet;
import java.util.function.Predicate;

public class LeftmostPrefixDemo {

    enum Status { CREATED, PAID, SHIPPED, DONE, CANCELLED }

    // Simulates the composite index (member_id, status, created_at), with order_id appended so every entry is unique
    record Entry(long memberId, Status status, LocalDate createdAt, long orderId) {}

    static final Comparator<Entry> INDEX_ORDER = Comparator.comparingLong(Entry::memberId)
            .thenComparing(Entry::status)
            .thenComparing(Entry::createdAt)
            .thenComparingLong(Entry::orderId);

    public static void main(String[] args) {
        NavigableSet<Entry> index = new TreeSet<>(INDEX_ORDER);
        Random random = new Random(7);
        long orderId = 0;
        for (long member = 1; member <= 2_000; member++) {
            for (int i = 0; i < 100; i++) {
                index.add(new Entry(member, Status.values()[random.nextInt(5)],
                        LocalDate.of(2026, 1, 1).plusDays(random.nextInt(320)), ++orderId));
            }
        }
        LocalDate since = LocalDate.of(2026, 10, 1);
        System.out.printf("The index has %,d entries%n%n", index.size());

        // 1. member_id = 42: equality on the leftmost column is one contiguous range
        report("member_id = 42", range(index, 42, null), e -> true);

        // 2. member_id = 42 AND status = PAID: equality on the first two columns, a narrower range
        report("member_id = 42 AND status = 'PAID'", range(index, 42, Status.PAID), e -> true);

        // 3. Equality on the first two columns + a range on the third: still one contiguous range, already sorted by created_at
        NavigableSet<Entry> paid = range(index, 42, Status.PAID);
        NavigableSet<Entry> recentPaid = paid.tailSet(new Entry(42, Status.PAID, since, 0), true);
        report("member_id = 42 AND status = 'PAID' AND created_at >= '2026-10-01'", recentPaid, e -> true);

        // 4. Skipping the middle column: only member_id locates the range; created_at can only filter entry by entry
        report("member_id = 42 AND created_at >= '2026-10-01'",
                range(index, 42, null), e -> !e.createdAt().isBefore(since));

        // 5. Skipping the leftmost column: nothing to locate with, so every entry in the index is checked
        report("status = 'PAID'", index, e -> e.status() == Status.PAID);
    }

    static NavigableSet<Entry> range(NavigableSet<Entry> index, long memberId, Status status) {
        Entry from = new Entry(memberId, status == null ? Status.CREATED : status, LocalDate.MIN, Long.MIN_VALUE);
        Entry to = status == null
                ? new Entry(memberId + 1, Status.CREATED, LocalDate.MIN, Long.MIN_VALUE)
                : new Entry(memberId, status, LocalDate.MAX, Long.MAX_VALUE);
        return index.subSet(from, true, to, false);
    }

    static void report(String where, NavigableSet<Entry> scanned, Predicate<Entry> filter) {
        long matched = scanned.stream().filter(filter).count();
        System.out.printf("%-68s scanned %,7d, matched %,5d%n", where, scanned.size(), matched);
    }
}
text
The index has 200,000 entries

member_id = 42                                                       scanned     100, matched   100
member_id = 42 AND status = 'PAID'                                   scanned      25, matched    25
member_id = 42 AND status = 'PAID' AND created_at >= '2026-10-01'    scanned       4, matched     4
member_id = 42 AND created_at >= '2026-10-01'                        scanned     100, matched    18
status = 'PAID'                                                      scanned 200,000, matched 40,121
  • The first three queries scan exactly the matching entries: the conditions run contiguously from the leftmost column, and the range keeps narrowing
  • The fourth skips the middle column, status: only member_id locates the range, and created_at can only filter entry by entry, so it scans 100 entries to find 18. MySQL’s Index Condition Pushdown (Using index condition) filters at the index level first and saves the trips back to the table, but the scanned range stays the same
  • The fifth skips the leftmost column: there is nothing to locate with, so it has to read through the whole index. The skip scan in MySQL 8.0.13 and later is an exception when the first column has very few distinct values, but you cannot rely on it

That gives the rules for designing a composite index:

  1. Equality columns first, range columns last: columns after a range condition can no longer be used to locate rows
  2. ORDER BY follows the index order: for scenario 2’s “paid orders sorted by time”, with (member_id, status, created_at) the data is already in order and needs no extra sort (EXPLAIN no longer shows Using filesort), and with LIMIT 20 it stops after reading 20 entries
  3. “Most selective column first” is not an iron rule: the query patterns decide the order. An equality condition that every query includes can reasonably go first, even if it is not very selective

The optimizer may not use your index

MySQL’s optimizer decides by cost. If many rows match the condition (say status = 'DONE' covers 80%), going back to the table for each of them costs more than a plain full table scan, so the optimizer picks the full scan. That is correct behavior, not a bug.

Check the execution plan with EXPLAIN, focusing on these columns:

Column What to look for
type Roughly from best to worst: const, eq_ref, ref, range, index (scans the whole index), ALL (full table scan)
key Which index was actually used; NULL means none
rows Estimated number of rows to examine
Extra Using index (covering index), Using index condition (ICP), Using filesort (extra sort), Using temporary (temporary table)

EXPLAIN gives estimates. EXPLAIN ANALYZE, available since MySQL 8.0.18, actually runs the query and lists the real time and row count of each step. When statistics are stale, the estimates go wrong; refresh them with ANALYZE TABLE.

Queries that defeat an index

Query Why the index cannot be used Rewrite
WHERE DATE(created_at) = '2026-11-11' The column is wrapped in a function, and the index stores the raw values created_at >= '2026-11-11' AND created_at < '2026-11-12'
WHERE phone = 0912345678 (phone is a VARCHAR) When comparing a string with a number, MySQL converts every row’s string to a number before comparing Add quotes; bind the parameter as a String in Java
WHERE name LIKE '%Chen' It starts with a wildcard, so there is no starting point to locate LIKE 'Chen%' can use the index; searching anywhere in the text needs a full-text index (see Full-Text Search and Inverted Indexes)
WHERE created_at + INTERVAL 1 DAY > NOW() The column is part of an expression Move the arithmetic to the other side: created_at > NOW() - INTERVAL 1 DAY
WHERE a = ? OR b = ? One index cannot locate rows by two columns at once If each column has its own index, an index merge may be used; if not, rewrite it as a UNION
The columns on the two sides of a JOIN have different character sets or collations Every row has to be converted before the comparison Make the column definitions match

Scenarios 3 and 4 are the first two. The last one often shows up when an old system is integrated with a new one: the old table is utf8, the new one utf8mb4.

The cost of an index

Every index is a B+Tree that has to be maintained:

  • Write amplification: every INSERT writes once to the primary key index and once to each secondary index. With 12 secondary indexes, every insert changes 13 trees; an UPDATE that changes an indexed column deletes one entry from that index and inserts another
  • Space: it is common for the indexes together to be larger than the data itself, and they also compete for buffer pool memory
  • Replica lag: heavier writes on the primary mean more replay work on the replicas
  • Unique indexes cost more: every write to a unique index first has to read the page to check for duplicates. In MySQL 8.0, changes to non-unique secondary indexes can wait in the change buffer and be merged later; but from MySQL 8.4 on, innodb_change_buffering defaults to none, so every change to a secondary index has to read its page right away

So the 12 indexes in scenario 5 are not free. To find unused indexes, MySQL’s sys.schema_unused_indexes lists the indexes that have not been used since the server started. Before dropping one, you can first hide it from the optimizer with a MySQL 8.0 invisible index (ALTER TABLE ... ALTER INDEX ... INVISIBLE), watch for a while, and drop it if nothing goes wrong.

Deep pagination: the cost of OFFSET

LIMIT 20 OFFSET 100000 means “find the first 100,020 rows and throw away the first 100,000”. The database cannot jump straight to row 100,001; it has to count its way there one row at a time (possibly going back to the table for each row). The deeper the page, the slower it gets: that is scenario 6.

Keyset pagination starts from “the position of the last row on the previous page” instead:

sql
SELECT id, created_at, amount
FROM purchase_order
WHERE member_id = ?
  AND (created_at < ? OR (created_at = ? AND id < ?))   -- (created_at, id) of the last row on the previous page
ORDER BY created_at DESC, id DESC
LIMIT 20;

Whatever the page number, it reads 20 rows down from one position in the index. id makes the sort order unique: two orders can fall in the same millisecond, and with created_at alone you would skip or repeat rows. As noted earlier, INDEX (member_id, created_at) in InnoDB already implicitly includes id, so this query runs entirely on the index.

Comparing options

Pagination

OFFSET pagination Keyset pagination
Performance on deep pages The deeper, the slower The same on every page
Jump to any page Yes No, only previous and next
New rows inserted while paging Rows may repeat or go missing Not affected
Sort requirements None The combination of sort columns must be unique (add the primary key)
Good for Back-office tools, small data sets, when page numbers are needed Infinite scroll, APIs, exporting large amounts of data

For pagination with Spring Data JPA’s Pageable, see the Spring Data JPA pagination post.

Index types

Type Good for Form in MySQL
B+Tree Equality, ranges, sorting, prefix matching InnoDB default
Hash Equality lookups only InnoDB’s adaptive hash index builds them automatically for hot spots; you cannot create one yourself
Full-text index Keywords anywhere in the text FULLTEXT (see Full-Text Search and Inverted Indexes)
Spatial index Geographic ranges SPATIAL (R-Tree, see Geohash and Geospatial Indexes)
Functional / Multi-valued Expression results, JSON arrays 8.0.13+ / 8.0.17+ (see SQL vs NoSQL)

In Java

1. Manage indexes with migrations

sql
ALTER TABLE purchase_order
    ADD INDEX idx_member_status_created (member_id, status, created_at),
    ALGORITHM = INPLACE, LOCK = NONE;

InnoDB’s online DDL keeps accepting reads and writes while the index is built. Spell out ALGORITHM = INPLACE, LOCK = NONE: if the operation cannot run online, it fails with an error instead of quietly locking the table. JPA’s @Table(indexes = ...) only takes effect when Hibernate generates the schema; production indexes should be managed by a migration tool such as Flyway, and @Index serves as documentation at most:

java
@Entity
@Table(name = "purchase_order",
       indexes = @Index(name = "idx_member_created", columnList = "member_id, created_at"))
public class PurchaseOrder {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "member_id", nullable = false)
    private long memberId;

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 16)
    private OrderStatus status;

    @Column(name = "created_at", nullable = false)
    private Instant createdAt;

    @Column(nullable = false)
    private BigDecimal amount;

    // constructors and getters omitted
}

2. Keyset pagination

java
public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, Long> {

    // first page
    List<PurchaseOrder> findByMemberIdOrderByCreatedAtDescIdDesc(long memberId, Pageable pageable);

    // next page: continue after the (createdAt, id) of the last row on the previous page
    @Query("""
            select o from PurchaseOrder o
            where o.memberId = :memberId
              and (o.createdAt < :createdAt or (o.createdAt = :createdAt and o.id < :id))
            order by o.createdAt desc, o.id desc
            """)
    List<PurchaseOrder> findNextPage(@Param("memberId") long memberId,
                                     @Param("createdAt") Instant createdAt,
                                     @Param("id") long id,
                                     Pageable pageable);
}

Because it returns a List rather than a Page, Spring Data applies only LIMIT and does not run an extra COUNT(*) (on a large table, COUNT(*) alone can be slow).

The cursor goes to the frontend, which sends it back to get the next page:

java
/** Page cursor: the (createdAt, id) of the last row on the previous page. It only decides where to start; it grants no permission. */
public record OrderCursor(Instant createdAt, long id) {

    public String encode() {
        String raw = createdAt.toEpochMilli() + ":" + id;
        return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8));
    }

    public static OrderCursor decode(String token) {
        String[] parts = new String(Base64.getUrlDecoder().decode(token), StandardCharsets.UTF_8).split(":");
        return new OrderCursor(Instant.ofEpochMilli(Long.parseLong(parts[0])), Long.parseLong(parts[1]));
    }
}
java
@Service
public class MyOrderQuery {

    private static final int PAGE_SIZE = 20;

    private final PurchaseOrderRepository repository;

    public MyOrderQuery(PurchaseOrderRepository repository) {
        this.repository = repository;
    }

    public record OrderPage(List<PurchaseOrder> orders, String nextCursor) {}

    /** memberId must come from the authenticated identity, not from a request parameter. */
    @Transactional(readOnly = true)
    public OrderPage page(long memberId, String cursor) {
        PageRequest limit = PageRequest.of(0, PAGE_SIZE);
        List<PurchaseOrder> orders;
        if (cursor == null) {
            orders = repository.findByMemberIdOrderByCreatedAtDescIdDesc(memberId, limit);
        } else {
            OrderCursor after = OrderCursor.decode(cursor);
            orders = repository.findNextPage(memberId, after.createdAt(), after.id(), limit);
        }
        String next = null;
        if (orders.size() == PAGE_SIZE) {
            PurchaseOrder last = orders.get(orders.size() - 1);
            next = new OrderCursor(last.getCreatedAt(), last.getId()).encode();
        }
        return new OrderPage(orders, next);
    }
}

What a cursor actually looks like:

text
MTc5NTE2MjUzMDEyMzo5MTgyNzM -> OrderCursor[createdAt=2026-11-20T08:15:30.123Z, id=918273]

Since Spring Data 3.1 there is also a built-in Scroll API (Window, ScrollPosition.keyset()). With derived queries it generates the same conditions automatically and appends the primary key to the end of the sort to keep it unique.

3. The IgnoreCase trap in derived queries

Spring Data’s findByEmailIgnoreCase generates UPPER(email) = UPPER(?). The column is wrapped in a function, so the index on email can no longer be used. MySQL’s default collation (for example utf8mb4_0900_ai_ci) is already case-insensitive, so plain findByEmail is enough.

Pitfalls and gotchas

  • The more indexes, the better: every index slows down writes, takes memory, and adds load on the replicas
  • Indexing a low-selectivity column on its own: status has only 5 values, and an index on it alone is almost never chosen
  • Duplicate indexes: if (a, b) already exists, creating (a) as well is redundant
  • Too little data in the test environment: with a few thousand rows, the optimizer often picks a full table scan, and the plan in production can be completely different. Check EXPLAIN for key queries with a data volume close to production
  • A UUID string as the primary key: every secondary index gets bigger, and random inserts cause page splits
  • Adding an index to a big table directly: even with online DDL, each replica has to build the same index again, and the changes behind it wait in the meantime, causing lag as long as the index build itself. For big tables, use a tool like gh-ost instead, or schedule it for off-peak hours
  • Deep pagination with OFFSET: the further back, the slower, and on a big table COUNT(*) is expensive by itself
  • IgnoreCase in a derived query: the column is wrapped in UPPER(), and the index stops working
  • Looking only at rows, not at the actual execution: estimates can be off; confirm with EXPLAIN ANALYZE or with Rows_examined in the slow query log

Security

  • Concatenating sort columns into SQL: ORDER BY cannot use parameter binding, so putting a column name sent by the client straight into the SQL is SQL injection. Spring Data’s Sort checks that the property name exists in the domain model, but JpaSort.unsafe(...) turns that protection off. The safest approach is to accept only a key and map it to a predefined sort:
java
/** Sort orders a client may choose: accepts only a key, never a column name or an expression. */
public final class OrderSorts {

    private static final Map<String, Sort> ALLOWED = Map.of(
            "newest", Sort.by(Sort.Order.desc("createdAt"), Sort.Order.desc("id")),
            "amount", Sort.by(Sort.Order.desc("amount"), Sort.Order.desc("id")));

    private OrderSorts() {
    }

    public static Sort of(String key) {
        Sort sort = ALLOWED.get(key);
        if (sort == null) {
            throw new IllegalArgumentException("Unsupported sort: " + key);
        }
        return sort;
    }
}
  • Arbitrary filters are a cheap DoS: if clients can run LIKE '%...%' on any column, every request is a full table scan, and an attacker can bring the database down without much traffic. Limit filterable columns to indexed ones, and set a query timeout (MySQL’s max_execution_time can cap how long a SELECT runs)
  • A cursor is not authorization: the cursor only decides where to start reading; the member_id in the query condition must come from the authenticated identity. If you change it so that “the cursor carries the member_id”, an attacker can edit the cursor and page through someone else’s orders. That is BOLA (Part 8)
  • Unique index errors leak whether an account exists: if sign-up replies “this email is already in use”, attackers can try emails one by one to find out who is a member (account enumeration). Give every caller the same reply, “confirmation email sent”, and let the email itself tell the person they already have an account

When to use it, and when not to

  • Create an index: for column combinations that are queried often, have selective enough conditions, and are read far more than written; columns that often appear together in WHERE, JOIN, and ORDER BY make a composite index
  • No index needed: small tables with a few thousand rows (a full table scan is fast enough), tables with very heavy writes and few queries, columns with only a handful of distinct values
  • When to re-evaluate: queries in the slow query log whose Rows_examined is far larger than Rows_sent; total index size approaching or exceeding the buffer pool; rising write latency or replica lag; sys.schema_unused_indexes showing indexes that have gone unused for a long time

References

Comments