All Projects → joinhandshake → knockoff

joinhandshake / knockoff

Licence: MIT License
A gem for easily using read replicas.

Programming Languages

ruby
36898 projects - #4 most used programming language
shell
77523 projects

Projects that are alternatives of or similar to knockoff

rails cursor pagination
Add cursor pagination to your ActiveRecord backed application
Stars: ✭ 21 (+10.53%)
Mutual labels:  ruby-gem, activerecord
Postgresql cursor
ActiveRecord PostgreSQL Adapter extension for using a cursor to return a large result set
Stars: ✭ 384 (+1921.05%)
Mutual labels:  ruby-gem, activerecord
Pluck to hash
Extend ActiveRecord pluck to return array of hashes
Stars: ✭ 275 (+1347.37%)
Mutual labels:  ruby-gem, activerecord
Mobility
Pluggable Ruby translation framework
Stars: ✭ 644 (+3289.47%)
Mutual labels:  ruby-gem, activerecord
activerecord-crate-adapter
Ruby on Rails ActiveRecord adapter for CrateDB
Stars: ✭ 27 (+42.11%)
Mutual labels:  ruby-gem, activerecord
Unscoped associations
🔦 Skip the default_scope in your associations (ActiveRecord)
Stars: ✭ 53 (+178.95%)
Mutual labels:  ruby-gem, activerecord
Ransack
Object-based searching.
Stars: ✭ 5,020 (+26321.05%)
Mutual labels:  ruby-gem, activerecord
activerecord-setops
Union, Intersect, and Difference set operations for ActiveRecord (also, SQL's UnionAll).
Stars: ✭ 21 (+10.53%)
Mutual labels:  ruby-gem, activerecord
filtered
Filters ActiveRecord queries in a nice way
Stars: ✭ 28 (+47.37%)
Mutual labels:  ruby-gem, activerecord
timeliness-i18n
Translations for timeliness and validates_timeliness gem.
Stars: ✭ 16 (-15.79%)
Mutual labels:  activerecord
katapult
Kickstart Rails development!
Stars: ✭ 21 (+10.53%)
Mutual labels:  ruby-gem
normalize attributes
Sometimes you want to normalize data before saving it to the database like down casing e-mails, removing spaces and so on. This Rails plugin allows you to do so in a simple way.
Stars: ✭ 41 (+115.79%)
Mutual labels:  activerecord
state inspector
State change & method call logger. A debugging tool for instance variables and method calls.
Stars: ✭ 24 (+26.32%)
Mutual labels:  ruby-gem
arca
Arca is a callback analyzer for ActiveRecord ideally suited for digging yourself out of callback hell
Stars: ✭ 23 (+21.05%)
Mutual labels:  activerecord
wharel
Arel made simple
Stars: ✭ 95 (+400%)
Mutual labels:  activerecord
mercadopago
A Ruby Object-oriented gem that facilitates the usage of Mercadopago's API.
Stars: ✭ 16 (-15.79%)
Mutual labels:  ruby-gem
minio-ruby
MinIO Client SDK for Ruby
Stars: ✭ 26 (+36.84%)
Mutual labels:  ruby-gem
rails-microservices-book
A guide to building distributed Ruby on Rails applications using Protocol Buffers, NATS and RabbitMQ
Stars: ✭ 23 (+21.05%)
Mutual labels:  activerecord
invokable
Objects are functions! Treat any Object or Class as a Proc (like Enumerable but for Procs).
Stars: ✭ 40 (+110.53%)
Mutual labels:  ruby-gem
eventually-jekyll-theme
A Jekyll version of the "Eventually" theme by HTML5 UP.
Stars: ✭ 26 (+36.84%)
Mutual labels:  ruby-gem

Knockoff

Build Status Gem Version

A gem for easily using read replicas.

🤝 Battle tested at Handshake

Library Goals

  • Minimal ActiveRecord monkey-patching
  • Easy run-time configuration using ENV variables
  • Opt-in usage of replicas
  • No need to change code when adding/removing replicas
  • Be thread safe

Supported Versions

Knockoff supports Rails 4, 5 and 6

Installation

Add this line to your application's Gemfile:

gem 'knockoff'

And then execute:

$ bundle

Or install it yourself as:

$ gem install knockoff

Usage

Initializer

Add an initializer at config/knockoff.rb with the below contents

Knockoff.enabled = true # NOTE: Consider adding ENV based disabling

Configuration

Configuration is done using ENV properties. This makes it easy to add and remove replicas at runtime (or to fully disable if needed). First, set up ENV variables pointing to your replica databases. Consider using the dotenv gem for manging ENV variables.

# .env

REPLICA_1=postgres://username:password@localhost:5432/database_name

The second ENV variable to set is KNOCKOFF_REPLICA_ENVS which is a comma-separated list of ENVS holding database URLs to use as replicas. In this case, the ENV would be set as follows.

# .env

KNOCKOFF_REPLICA_ENVS=REPLICA_1

Note that it can be multiple replicas, and knockoff will use both evenly:

KNOCKOFF_REPLICA_ENVS=REPLICA_1,REPLICA_2

Lastly, knockoff will read the 'knockoff_replicas' database.yml config for specifying additional params:

# database.yml

knockoff_replicas:
  <<: *common
  prepared_statements: false

Basics

To use one of the replica databases, use

Knockoff.on_replica { User.count }

To force primary, use

Knockoff.on_primary { User.create(name: 'Bob') }

Using in Controllers

A common use case is to use replicas for GET requests and otherwise use primary. A simplified use case might look something like this:

# application_controller.rb

around_action :choose_database

def choose_database(&block)
  if should_use_primary_database?
    Knockoff.on_primary(&block)
  else
    Knockoff.on_replica(&block)
  end
end

def should_use_primary_database?
  request.method_symbol != :get
end

Replication Lag

Replicas will often be slightly behind the primary database. To compensate, consider "sticking" a user who has recently made changes to the primary for a small duration of time to the primary database. This will avoid cases where a user creates a record on primary, is redirected to view that record, and receives a 404 error since the record is not yet in the replica. A simple implementation for this could look like:

# application_record.rb

after_commit :track_commit_occurred_in_request

# If any commit happens in a request, we record that and have the logged_in_user
# read from primary for a short period of time.
def track_commit_occurred_in_request
  RequestLocals.store['commit_occurred_in_current_request'] = true
end

# application_controller.rb

after_action :force_leader_if_commit

def force_leader_if_commit
  if RequestLocals.store['commit_occurred_in_current_request'].to_b
    session[:use_leader_until] = Time.current + FORCE_PRIMARY_DURATION
  end
end

Then, in your should_use_primary_database? method, consult session[:use_leader_until] for the decision.

Run-time Configuration

Knockoff can be configured during runtime. This is done through the establish_new_connections! method which takes in a hash of new configurations to apply to each replica before re-connecting.

Knockoff.establish_new_connections!({ 'pool' => db_pool })

For example, to specify a puma connection pool at bootup your code might look something like

# puma.rb

db_pool = Integer(ENV['PUMA_WORKER_DB_POOL'] || threads_count)
# Configure the database connection to have the new pool size and re-establish connection
database_config = ActiveRecord::Base.configurations[Rails.env] || Rails.application.config.database_configuration[Rails.env]
database_config['pool'] = db_pool
ActiveRecord::Base.establish_connection(database_config)
Knockoff.establish_new_connections!({ 'pool' => db_pool })

Forking

For forking servers, you may disconnect all replicas before forking with Knockoff.disconnect_all!.

# puma.rb

before_fork do
  ActiveRecord::Base.connection_pool.disconnect!
  Knockoff.disconnect_all!
end

Other Cases

There are likely other cases specific to each application where it makes sense to force primary database and avoid replication lag. Good candidates are time-based pages (a live calendar, for example), forms, and payments.

Usage Notes

  • Do not use prepared statements with this gem

Development

After checking out the repo, run bin/setup to install dependencies. Then, run rake spec to run the tests. You can also run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release, which will create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/joinhandshake/knockoff.

License

The gem is available as open source under the terms of the MIT License.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].