Increase JSON datetime precision to include miliseconds
Summary
Current Rails application configuration defines JSON encoding precision for datetime values to 3 while our Postgres database stores 6 digits. Example:
time = User.first.created_at # Wed, 19 Mar 2025 16:21:34.160608000 UTC +00:00
time.to_json # 2025-03-19T16:21:34.160Z
Time.zone.parse(JSON.parse(time.to_json)) # Wed, 19 Mar 2025 16:21:34.160000000 UTC +00:00
That creates data losses when working in async fashion. For example in Sidekiq workers or Redis where time values converted to JSON strings for serialization. Live example
Proposed solution
Increase serialization precision to 6 digits app-wide so no data loss happens when we serialize and deserialize timestamp from DB.
ActiveSupport::JSON::Encoding.time_precision = 6
time = User.first.created_at # Wed, 19 Mar 2025 16:21:34.160608000 UTC +00:00
time.to_json # 2025-03-19T16:21:34.160608Z
Time.zone.parse(JSON.parse(time.to_json)) # Wed, 19 Mar 2025 16:21:34.160608000 UTC +00:00