Bitsets for opening hours

Map restaurant IDs to bit positions and minutes to sets of open restaurants, so GET /v1/restaurants can calculate is_open from memory.

Learning outcomes

  • Convert opening times into minute-of-the-day values in Asia/Kolkata.
  • Represent ordinary and overnight slots as half-open minute ranges.
  • Map restaurant IDs to bit positions across uint64 words.
  • Build and query per-minute bitsets, including restaurants beyond position 64.
  • Estimate the index's memory requirements and query cost.

Every restaurant in GET /v1/restaurants needs an is_open value for the requested time. The open_slots table stores daily opening and closing minutes, but checking every slot in SQL for every listing request repeats the same calculation while the clock remains in the same minute.

You can calculate the result once when the opening-hours data is loaded, then answer each request from an in-memory open-hours index. The key is to organize the data around the question you need to answer: which restaurants are open at minute 660?

Minute-of-the-day values

Represent opening hours as minutes since local midnight in Asia/Kolkata.

Midnight is minute 0. The last minute of the day starts at minute 1439, which represents 23:59. A day therefore contains 1,440 possible minute positions.

A slot stores its opening and closing minutes alongside its restaurant ID:

go
type Slot struct {
    RestaurantID int64
    OpenMin      int
    CloseMin     int
}

For example, a restaurant open from 08:00 to 13:00 has OpenMin = 480 and CloseMin = 780.

The database stores open_min from 0 through 1439 and close_min from 0 through 1440. The value 1440 represents the end of the day, not another minute that can be queried.

Convert a clock time using:

go
m := h*60 + min

Here, h is the hour in the local clock, and min is the minute within that hour. For 08:00, that gives 8*60 + 0 = 480. For 13:00, it gives 13*60 + 0 = 780.

This representation makes opening-hour comparisons integer operations. It also gives every daily schedule the same range of possible minute positions.

Half-open slots

A slot is a Half-open interval: its opening minute is included and its closing minute is excluded.

For a slot from 08:00 to 13:00, the interval is [480, 780). It covers minutes 480 through 779.

Consider these boundaries:

TimeMinuteOpen?
07:59479No
08:00480Yes
12:59779Yes
13:00780No

This convention makes adjacent slots work without overlapping at their boundaries. A restaurant closing at 13:00 and opening again at 14:00 has a clear closed period between the two slots.

Overnight slots

Some restaurants remain open after midnight. Consider a restaurant open from 22:00 until 03:00.

Its opening minute is 1320. Its closing minute is 180. Since the closing minute is not after the opening minute, the slot crosses midnight.

The daily index cannot represent a range that extends beyond minute 1440. Split the overnight slot into two half-open intervals:

  • The remaining part of the first day: [1320, 1440).
  • The beginning of the next day: [0, 180).

The two intervals represent the same slot and use the same restaurant ID.

22:00 = 1320
03:00 = 180

[1320, 1440)
[0, 180)

The restaurant is open at 22:00, 23:59, 00:00 and 02:59. It is closed at 03:00.

A slot from minute 0 to minute 1440 is a different case. Its closing minute is after its opening minute, so [0, 1440) covers the entire day.

Multiple slots

A restaurant can have several independent slots during one day.

For example, restaurant 1 has these schedules:

OpeningClosing
08:0010:00
12:0015:00
22:0001:00

The first two slots produce ordinary ranges. The third produces two ranges because it crosses midnight.

The restaurant is open during any of these ranges. Gaps between them remain closed.

Days of the week are outside this week's implementation. Treat the supplied slots as a repeating daily schedule. Supporting different weekday and weekend schedules would require the lookup model to account for the day as well.

Bitsets for restaurant membership

Once you convert schedules into minute ranges, the remaining question is a membership lookup:

Which restaurants are open at minute 660?

A Bitset stores many boolean values compactly. Each restaurant receives one bit position. A set bit means that restaurant is open at the corresponding minute. An unset bit means it is closed.

Go's uint64 contains 64 bits. With zero-based restaurant positions, position p maps to a word and a bit within that word:

wordIndex = p / 64
bitIndex  = p % 64

For example:

Restaurant positionWordBit
000
63063
6410
13022
19937

Positions 0 through 63 fit in the first word. Position 64 starts the second word.

For n restaurants, the number of words required per minute is ceil(n / 64).

Two hundred restaurants therefore require four words per minute. Three words hold only 192 bits.

The per-minute index

Store one bitset for every minute of the day. A convenient representation has an ID mapping and an array of minute-specific words:

go
const minutes = 24 * 60

type Index struct {
    ids    []int64
    openAt [minutes][]uint64
}

The ids slice maps bit positions back to restaurant IDs. If ids[3] is 42, position 3 represents restaurant 42.

The openAt array has 1,440 entries. Each entry contains enough uint64 words to represent every restaurant in the index.

For example, if restaurant 42 is open at minute 600, its corresponding bit is set in openAt[600].

A matrix with minutes as rows and 64-bit restaurant words as columns. Set bits identify restaurants open at each minute. Reading one minute's row returns the restaurants open at that time.A matrix with minutes as rows and 64-bit restaurant words as columns. Set bits identify restaurants open at each minute. Reading one minute's row returns the restaurants open at that time.

This arrangement makes time lookup direct. Once you know the minute, you select one entry in openAt instead of scanning every opening-hours slot.

Building the index

Building the index has two main costs: assigning restaurant positions and setting bits for the minutes covered by each slot.

Assign one position to each distinct restaurant ID. Every slot belonging to that restaurant must use the same position. Otherwise, separate opening periods would incorrectly appear to belong to different restaurants.

For example, if restaurant 42 has three slots, all three slots must update the bit associated with restaurant 42.

After assigning positions, allocate enough words for every minute. With 200 restaurants, each minute needs four uint64 words.

To mark a restaurant open over a range, calculate its word and bit position, then use a bitwise OR. Since Index.openAt is an array, the marking function takes a pointer to that array:

go
func mark(openAt *[minutes][]uint64, p, from, to int) {
    for m := from; m < to; m++ {
        word := p / 64
        bit := uint(p % 64)
        openAt[m][word] |= uint64(1) << bit
    }
}

Pass the address of the array when calling it, for example, mark(&x.openAt, p, from, to).

The left shift creates a value with one set bit. The OR operation combines it with the existing word without changing other restaurants' bits.

The loop stops before to. A range from minute 480 to minute 780 therefore marks exactly 300 minute positions.

For a normal slot, mark [open_min, close_min). For an overnight slot, mark [open_min, 1440) and [0, close_min).

Notice that multiple slots can safely set the same restaurant bit in a minute. OR does not clear an existing bit, so overlapping slots do not change the result.

A restaurant with no slots has no set bits and is closed at every minute. The restaurant list can leave its is_open value false when its ID does not appear among the open restaurants.

The build cost is proportional to the total number of open minutes across the supplied slots. You pay this cost when building the index rather than on every listing request. Loading the slot records together also follows the Batch loading principle used earlier in the course: avoid repeating database reads for data that can be reused.

Reading open restaurants

A lookup starts by selecting the bitset for one minute.

go
func openAtMinute(x *Index, minute int) []int64

For each word in that minute's bitset, you need to find the set bits and map their positions back to restaurant IDs.

Scanning every possible bit individually would work, but you can skip unset bits.

Finding the lowest set bit

For a nonzero uint64 word, this expression isolates its lowest set bit:

go
lowest := word & -word

Go uses two's-complement integer arithmetic. For unsigned integers, arithmetic wraps modulo 2^64. Negating a word therefore preserves its lowest set bit when combined with the original word using AND.

Here is a concrete example using 8-bit binary values. The same operation applies to a uint64, which wraps modulo 2^64:

word       = 0b01101000
-word      = 0b10011000
word & -word = 0b00001000

The result contains only the lowest set bit, at position 3. The higher set bits are removed.

The math/bits package provides a function to find its position:

go
bit := bits.TrailingZeros64(lowest)
position := wordIndex*64 + bit

TrailingZeros64 counts the zero bits to the right of the lowest set bit. Because lowest contains exactly one set bit, the result is its position within the word.

Combine that position with the word index to get the global restaurant position. Then retrieve the ID using ids[position].

After processing the restaurant, clear its bit from the local word:

go
word &^= lowest

The &^ operator is Go's bit-clear operator. It clears the bit selected by lowest while preserving every other set bit.

You can repeat this process until the local word becomes zero:

go
for word != 0 {
    lowest := word & -word
    bit := bits.TrailingZeros64(lowest)
    position := wordIndex*64 + bit
    openIDs = append(openIDs, ids[position])
    word &^= lowest
}

Each iteration visits one set bit. Because word is a local copy from the range loop, clearing its bits does not modify the index.

The query does not need to inspect each restaurant individually. It scans the words in the selected minute's bitset and visits the restaurants represented by set bits.

Memory and query cost

The bitset payload has a predictable memory requirement. Every minute stores one uint64 for each group of up to 64 restaurants.

The total is:

bytes = 1440 * ceil(n / 64) * 8

For 10,000 restaurants, you need 157 words per minute:

1440 * 157 * 8 = 1,808,640 bytes

That is approximately 1.8 MB of bitset data. This excludes the restaurant ID slice and Go's slice and allocation overhead.

The query scans one word per 64 restaurants, so the word-scanning cost is O(n / 64). It also needs to process the set bits that represent open restaurants.

For sparse results, the number of set bits can be much smaller than the total number of restaurants. This avoids a per-restaurant check for every listing request.

Building the index costs O(total open minutes). This is a useful trade when opening-hours data changes less frequently than the restaurant list is requested.

Local time and offsets

A minute-of-the-day value represents local wall-clock time. A slot from 08:00 to 13:00 means those clock times in Asia/Kolkata, not UTC.

The API accepts an optional RFC 3339 at timestamp. Such a timestamp represents an absolute instant and can carry different UTC offsets. Convert it into the course's timezone before extracting its hour and minute.

go
loc, err := time.LoadLocation("Asia/Kolkata")
if err != nil {
    return err
}

localAt := at.In(loc)
minute := localAt.Hour()*60 + localAt.Minute()

Consider a slot from 11:00 to 12:00:

Supplied timestampKolkata timeOpen?
2026-01-05T05:30:00Z11:00Yes
2026-01-05T05:29:00Z10:59No
2026-01-05T14:45:00+09:0011:15Yes
2026-01-05T11:15:00+09:0007:45No

The instant stays the same during conversion. Only its displayed local clock time changes.

When at is absent, use the current time converted to the same location:

go
localNow := time.Now().In(loc)
minute := localNow.Hour()*60 + localNow.Minute()

The index itself does not perform timezone conversion. It reads the hour and minute from the time.Time it receives. The caller must supply a time in the correct location.

This course uses Asia/Kolkata for all restaurants. If restaurants in different time zones were added, a single minute-of-the-day lookup would not be enough. You could maintain separate indexes by timezone or extend the lookup model to account for each restaurant's location.

Immutable indexes

After building the index, treat it as read-only. Do not modify ids or the bitsets while HTTP handlers are querying it.

Multiple handlers can safely read the same completed index concurrently. Each handler reads shared data and works with local copies of the words. Each lookup also constructs its own result slice.

This property matters when the opening-hours data changes. You should build a complete replacement rather than modifying the index that current requests are reading. The next lesson covers how a context-owned background refresh publishes a replacement snapshot.

The restaurant list lookup

The open-hours index turns a collection of database slots into a reusable answer for each minute of the day. It keeps the database records as the source of truth while making repeated opening-status lookups independent of request traffic.

The GET /v1/restaurants: open status exercise connects this lookup to the restaurant list. Every listed restaurant needs an is_open boolean evaluated at the supplied at timestamp or at the current Kolkata time. Your index needs to handle ordinary slots, overnight slots and restaurants with no opening-hours records.

Check your understanding

Question 1 of 4

A restaurant has a slot from 11:00 to 23:00. Should it appear open at exactly 23:00?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (Go 1.25, math/bits).

Finished Lesson 2.15?