How can I improve the performance of your RailS application?

Source: Internet
Author: User

is rails slow?

"The railroad is slow," you may have heard the joke, what about our Rails framework?
If rails is slow, then how to improve the performance of the rails APP is a problem that developers are most concerned about.

Maybe you've heard a lot of ways to improve the performance of RoR apps, which are hard to find, and we need to choose the one that best helps developers get out of the performance dilemma.

Here are a few different ways to improve the performance of the Rails application.

1. Database indexing

Your APP is limited by DB performance, and a good database index can give you 100 times times the performance boost in a large database table. However, not all Rails developers understand how important this is.

Adding indexes is easy:

class AddIndexToClientIndustry < ActiveRecord::Migration    def change        add_index :client_industries, :client_id    endend

Next, there is no Index of the situation to make a comparison.

There is the case of Index:

CREATE INDEX addresses_addressable_id_addressable_type_idx  ONaddresses  USING btree  (addressable_id,addressable_type);t1 = Time.now c = Company.find(178389) a = c.addresses.firstt2 = Time.nowputs "---Operation took #{t2-t1} seconds---”Result with index:---Operation took 0.012412 seconds---

There is no case for Index:

DROP INDEXaddresses_addressable_id_addressable_type_idx;t1 = Time.now c = Company.find(178389) a = c.addresses.firstt2 = Time.nowputs "---Operation took #{t2-t1} seconds---”Result without index:---Operation took 0.378073 seconds---

0.378073/0.012412 = 30.46 No index is 30.46 seconds slower than index.

The engineer can therefore add Indexes to all reference parameters, or to other frequently queried parameters. But not too much, because each one will increase the DB Size to affect performance.

2. Number of database queries

Ror makes programming faster, but in turn makes it difficult to control the number of database queries per request. For example, if each Client has one or more Industries. We want to show the Client List and their Primary Industries:

<% @clients.each do |client| %>  <tr>      <td><%= client.id %></td>      <td><%= client.business_name %></td>      <td><%= client.industries.first.name %></td>  </tr><% end %># app/controllers/clients_controller.rbdef index    @clients = Client.allend

If there are 50 clients, then there will be 51 database queries:

    Processing by ClientsController#index as HTML    SELECT "clients".* FROM "clients"     SELECT "industries".* FROM "industries" INNER JOIN "client_industries" ON "industries"."id" = "client_industries"."industry_id" WHERE "client_industries"."client_id" = 1 LIMIT 1    SELECT "industries".* FROM "industries" INNER JOIN "client_industries" ON "industries"."id" = "client_industries"."industry_id" WHERE "client_industries"."client_id" = 2 LIMIT 1    SELECT "industries".* FROM "industries" INNER JOIN "client_industries" ON "industries"."id" = "client_industries"."industry_id" WHERE "client_industries"."client_id" = 3 LIMIT 1    …

Solution: Eager Loading

# app/controllers/clients_controller.rbdef index    @clients = Client.includes(:industries).allend

There are now only 2 to 3 database queries rather than 51:

    Processing by ClientsController#index as HTML    SELECT "clients".* FROM "clients"     SELECT "client_industries".* FROM    "client_industries" WHERE    "client_industries"."client_id" IN (1, 2, 3)    SELECT "industries".* FROM "industries" WHERE "industries"."id" IN (1, 5, 7, 8, 4)
3. Reduce memory consumption
    • Use only the gems you really need
    • Reload objects when used
    • Batch processing of massive amounts of data.

An example of using real data--find_each:

Using Find:
t1 = Time.now  Company.where(:country_id=>1).find do |c|puts "do something!" if [‘Mattski Test‘].include?(c.common_name)endt2 = Time.nowputs "---Operation took #{t2-t1} seconds---”
Result:
1 query, taking 46.65 seconds
Now using Find_each:
t1 = Time.now  Company.where(:country_id=>1).find_each do |c|    puts "do something!" if [‘Mattski Test‘].include?(c.common_name)end  t2 = Time.nowputs "---Operation took #{t2-t1} seconds---"
Result:
100 queries, taking 15.53 seconds in total (3x faster)

There are more queries than the situation is fast.

4. Using the cache

The use of caching has a huge impact on performance, first ensuring that the data model is correct, and caching can help you hide structural problems.

    • Object Cache
      In the case of object caching, the include of the query method should be removed to avoid the inability of the associated query to take advantage of the caching phenomenon.

    • Query cache
      In the case where real-time is not required, the query results can be cached into memcached using memcache-client for the time-consuming query of the statistics class.

    • Page Local Cache
      Both the object cache and the query cache reduce the database access load, but if the RoR load is high, it can only rely on page local caching.

"web2.0 Web site comparison commonly used page local cache, Rails page local cache has a disadvantage, that is, and the page query results corresponding to the action of the query statement to be placed in the View, or each action inside the query will be executed, But doing so destroys the MVC structure with good program code. In this case, you can also use another cache plugin: better rails caching to cache the query statements in the Action while caching the page. 」

5. Make Web Requests faster

Only a small number of available processes are used for service Web requests, so Web requests need to be made faster. Ideally, the web process typically completes in milliseconds, 1-2 seconds is slow, and more than 10 seconds is very slow. If your Web request is slow, your rails APP will not be able to support a large number of users at the same time.

Solution: Run with background
Use the background to run a long-running project such as delayed jobs to free up your web process to resolve more requests.

6. Performance monitoring

Performance monitoring of the APP makes it easy to find out which parts are running slowly or even quickly, and you can take advantage of the best OneAPM monitoring tools available in the domestic application monitoring.

OneAPM for Ruby enables application performance management and monitoring within all Ruby applications, including visibility of code-level capability issues, rapid identification and traceability of performance bottlenecks, real user experience monitoring, Server monitoring and end-to-end application performance management. Trace performance bottlenecks to: poorly performing SQL statements, third-party APIs, Web Services, Caching Layers, background tasks, and more.

This is an overview page for monitoring using OneAPM, where you can get a preliminary impression of how long the request will take on the server side. Can visually see the different time web things, background tasks, database and external services, the level of response time, throughput, number of executions and other indicators, the graph of Web things in 15:41 when the response time peaks, slow response.

To further determine the problem, point to the Web interface to learn more about the response time ratio of each slow thing, and quickly locate api/medicines/index the response time is longer.

Clicking on the wrong request address will list the URL of the error, the first and last occurrences, the number of times the error occurred, the Agent name that was detected, the error message, and the stack information.

Good application performance monitoring often takes a lot of time and effort, so choosing a good third-party monitoring tool will greatly improve operational efficiency, which can help improve the performance of your Rails APP.

7. Using the In-memory database

When both the query and the sort are done in memory, the database will run faster, and they need to be slow to run on disk.

Solution:

    • Limit the size of the DB to ensure it is fully fit for memory.
    • Move non-urgent information out of the primary database and into the secondary database or somewhere else.
    • If you have a large number of storage requirements, consider using a non-relational database.
8. More Performance Recommendations:
    • Use content distribution networks for static files, such as using AWS CloudFront.
    • Use lazy loading for add-ons that require 1-2 seconds.
    • Use a service-oriented architecture that enables some processes to synchronize on the managed stack.

Believe that choose one or several suitable performance promotion method, can make RoR APP more user satisfaction.

Note: This article references and translates some of Matt Kuklinski's shared content on SlideShare to improve Rails performance.

This article is compiled and collated by OneAPM engineers. OneAPM is an emerging leader in application performance management, enabling enterprise users and developers to easily implement slow program code and real-time crawling of SQL statements. To read more technical articles, please visit the OneAPM official blog.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

How can I improve the performance of your RailS application?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.