This content has been automatically translated from Ukrainian.
RangeError can be seen in Ruby on Rails after trying to write a number that is too large (or too small) to the database. The error may look like this:
999999999999999999999999999999999999999 is out of range for ActiveModel::Type::Integer with limit 4 bytes or 999999999999999999999999999999999999999 is out of range for ActiveRecord::Type::Integer with limit 4
This means that we are trying to shove something into the database that is outside the allowed range.
For numbers in the database, we can use the data types int and bigint. And each of these types has its own limitations. I have already written about this in the post about the difference between int and bigint.
I will duplicate it here as well:
- Int can have values between -2147483648 and 2147483647.
- Bigint between -9223372036854775808 and 9223372036854775807.
So these are architecture-fixed limits for int (32-bit number) and bigint (64-bit number).
The error can be resolved by using numbers within these ranges. Sometimes this error occurs when testing inputs on the frontend. QA enters a large number into a field and we get a RangeError. This is usually fixed by adding validations and limits (both on the fe and be sides).
But what to do if this is a model id and we need a larger range of possible values? There are actually several options.
- Switching from ID to UUID (Universally Unique Identifier). There can be quite a few variations of implementation. It depends on the stack and scope.
- Sharding the database into clusters. There are also many variations of implementations here. But conditionally - each cluster (shard) will have a prefix and its own range of bigint.
- In large systems, you can see composite keys that are created from several different columns. But this is also a specific option, the implementation of which depends on many factors.
This post doesn't have any additions from the author yet.