Showing posts with label puma. Show all posts
Showing posts with label puma. Show all posts

Thursday, March 1, 2018

Table name corruption errors in ActiveRecord

Leave a Comment

Sporadically we get PG::UndefinedTable errors while using ActiveRecord. The association table name is some how corrupted and I quite often see Cancelled appended to the end of the table name.

E.g:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "fooCancell" does not exist  ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "Cancelled" does not exist ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  relation "barC" does not exist 

In the example above, I have obfuscated the table name by using foo and bar.

We see this errors when the rails project is running inside Puma. Queue workers seems to be doing okay.

The tables in the error message doesn't correspond to real tables or models. It looks like the case of memory corruption. Has anyone seen such issues? If so how did you get around it?

puma.rb

on_worker_boot do   ActiveRecord::Base.establish_connection end 

database.yml

production:   url:  <%= ENV["DATABASE_URL"] %>   pool: <%= ENV['DB_CONNECTION_POOL_SIZE'] || 5%>   reaping_frequency: <%= ENV['DB_CONNECTION_REAPING_FREQUENCY'] || 10 %>   prepared_statements: false 

2 Answers

Answers 1

It looks like reaping_frequency may be the issue. I found a couple claims that they may have a threading bug. I would try removing that option or setting it to nil and see if that works. The only other thing I can think of is if you are manually calling Thread.new and using active record within it. Here are the few claims against reaping:

http://omegadelta.net/2014/03/15/the-rails-grim-reaper/

https://github.com/mperham/sidekiq/issues/1936

Search for "DO fear the Reaper" here: https://www.google.com/amp/s/bibwild.wordpress.com/2014/07/17/activerecord-concurrency-in-rails4-avoid-leaked-connections/amp/

Answers 2

I'm hazarding a guess here...

But you might be either:

  1. calling fork within your application; OR
  2. calling ActiveRecord routines (using database calls) before the server (puma) is forking it's worker processes (during the app initialization).

Either of these will break ActiveRecord's synchronization and cause multiple processes to share the database connection pool without synchronizing it's use (resulting in interlaced and corrupt database commands).

If you are using fork, make sure to close all the ActiveRecord database connections and reinitialize the connection pool (there's a function call that does it, but I don't remember it of the top of my head, maybe ActiveRecord.disconnect! or ActiveRecord.connection_pool.disconnect!).

Otherwise, before running Puma (either during the initialization process or using Puma's at_fork), close all the ActiveRecord database connections and reinitialize the connection pool.

Read More

Friday, August 12, 2016

Rails query execution causes database spikes

Leave a Comment

I'm having a problem with my Rails application where some random queries take around 5 seconds or longer to finish. Most of the time the queries are very simple (select * from x where id = ?) and the fields are even indexed too.

Here's some more information about the setup:

  • Puma 3.5.0 behind a reversed nginx proxy
    • 4 workers with minimum 4, max 8 threads each.
  • Ruby v2.2.3, Rails v4.2.4
  • PostgreSQL 9.4 database
    • Thread pool set to max 60 connections
  • Appsignal for monitoring
  • 8GB RAM, 4 CPU's, SSD.

I found this out when looking at the query performance in Appsignal. I noticed most queries finishing in a few ms and then every now and then, still in the same request, there are multiple queries that take 5+ seconds to finish. And the odd part is that it ALWAYS takes 5,.. seconds. Here's a picture of that in action: Appsignal performance

Things I've tried:

  • Increase the thread pool to make sure the puma worker threads have enough connection objects.
  • Set 'reaping_frequency' to 10s to make sure there are no dead connections being used.
  • Increase puma workers/threads

I'm noticing this in the application as there are some pages that take a long time to load (I have a function call that takes about 1 minute to finish) and somehow this is blocking new requests. This is strange to me as there are 4 workers each with 8 threads = 32 threads that can handle the other requests.

I ran an explain on the query in the picture above, this is the output:

Limit  (cost=0.28..8.30 rows=1 width=150)   ->  Index Scan using index_addresses_on_addressable_id_and_addressable_type on addresses  (cost=0.28..8.30 rows=1 width=150)         Index Cond: ((addressable_id = 1) AND ((addressable_type)::text = 'University'::text))         Filter: (deleted_at IS NULL) Total query runtime: 13 ms 

And this is the schema of the addresses table:

# Table name: addresses # #  id               :integer          not null, primary key #  street           :string #  zip_code         :string #  city             :string #  country          :string #  addressable_id   :integer #  addressable_type :string #  created_at       :datetime         not null #  updated_at       :datetime         not null #  street_number    :string #  latitude         :float #  longitude        :float #  mobile           :string #  phone            :string #  email            :string #  deleted_at       :datetime #  name             :string` 

Here's my Puma config file:

#!/usr/bin/env puma  directory '/home/deployer/apps/qeystate/current' rackup "/home/deployer/apps/qeystate/current/config.ru" environment 'staging'    pidfile "/home/deployer/apps/qeystate/shared/tmp/pids/puma.pid" state_path "/home/deployer/apps/qeystate/shared/tmp/pids/puma.state" stdout_redirect '/home/deployer/apps/qeystate/shared/log/puma_access.log', '/home/deployer/apps/qeystate/shared/log/puma_error.log', true threads 4,8 bind 'unix:///home/deployer/apps/qeystate/shared/tmp/sockets/puma.sock' workers 4 preload_app! prune_bundler  on_worker_boot do   ActiveSupport.on_load(:active_record) do     ActiveRecord::Base.establish_connection   end end  before_fork do   ActiveRecord::Base.connection_pool.disconnect! end 

0 Answers

Read More

Wednesday, April 20, 2016

How can I serve assets in /public that are not part of the asset pipeline with puma/nginx?

Leave a Comment

This is an AWS question, I'm using the Ruby 2.2 (Puma) platform.

My compiled assets (in /public/assets) are served as expected. The other assets in /public are not being served (404).

Where do I configure this? Is this an nginx problem? or a puma problem?

Or is this just an AWS image issue?

Here's a live example (robots.txt should be served from the root): http://staging.us-west-2.elasticbeanstalk.com/public/robots.txt

It's also worth mentioning that the default Passenger platform image works out of the box.

2 Answers

Answers 1

So, i'm using the exact same environment and I found the solution with a little google fu:

With rails 4+, in the file:

/config/environments/production.rb 

you should find the following lines near the top of the file

# Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? 

That's all fine and dandy since we're using passenger(nginx or apache), but Puma doesn't handle this for us :)

To resolve this...

In your AWS console, go to your elastic beanstalk dashboard for the project in question, and click 'Configuration' on the left-hand menu.

Now click the little gear icon in the box titled 'Software Configuration'

Now you should see a table under 'Environment Properties', enter 'RAILS_SERVE_STATIC_FILES' into a new field under 'Property Name', then type 'true' (without the quotes) into the value field, hit apply.

Viola! Now your project is serving static files :)

Answers 2

In case it helps anyone, or someone knows how to improve it, here's the nginx config that finally got it working for me. In /.ebextensions/01_files.config:

files:     "/etc/nginx/conf.d/webapp_healthd.conf" :         mode: "000755"         owner: root         group: root         content: |             upstream my_app {               server unix:///var/run/puma/my_app.sock;             }              log_format healthd '$msec"$uri"'                             '$status"$request_time"$upstream_response_time"'                             '$http_x_forwarded_for';              server {               listen 80;               server_name _ localhost; # need to listen to localhost for worker tier               root /var/app/current/public;                if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") {                 set $year $1;                 set $month $2;                 set $day $3;                 set $hour $4;               }                access_log  /var/log/nginx/access.log  main;               access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd;                try_files $uri/index.html $uri @my_app;                location @my_app {                 proxy_pass http://my_app; # match the name of upstream directive which is defined above                 proxy_set_header Host $host;                 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;               }                location /assets {                 alias /var/app/current/public/assets;                 gzip_static on;                 gzip on;                 expires max;                 add_header Cache-Control public;               }             }     "/opt/elasticbeanstalk/hooks/appdeploy/post/03_restart_nginx.sh":         mode: "000755"         owner: root         group: root         content: |             #!/usr/bin/env bash             rm /etc/nginx/conf.d/webapp_healthd.conf.bak             rm /etc/nginx/conf.d/custom.conf                         service nginx restart 
Read More