Category: Ruby

  • How Sequel and Sinatra Solve Ruby’s API Problem

    How Sequel and Sinatra Solve Ruby’s API Problem

    Introduction

    In recent years, the number of JavaScript single page application frameworks and mobile applications has increased substantially. This imposes a correspondingly increased demand for server-side APIs. With Ruby on Rails being one of the today’s most popular web development frameworks, it is a natural choice among many developers for creating back-end API applications.
    Yet while the Ruby on Rails architectural paradigm makes it quite easy to create back-end API applications, using Rails only for the API is overkill. In fact, it’s overkill to the point that even the Rails team has recognized this and has therefore introduced a new API-only mode in version 5. With this new feature in Ruby on Rails, creating API-only applications in Rails became an even easier and more viable option.
    But there are other options too. The most notable are two very mature and powerful gems, which in combination provide powerful tools for creating server-side APIs. They are Sinatra and Sequel.
    Both of these gems have a very rich feature set: Sinatra serves as the domain specific language (DSL) for web applications, and Sequel serves as the object-relational mapping (ORM) layer. So, let’s take a brief look at each of them.
    API With Sinatra and Sequel: Ruby Tutorial

    Ruby API on a diet: introducing Sequel and Sinatra.

    Sinatra

    Sinatra is Rack-based web application framework. The Rack is a well known Ruby web server interface. It is used by many frameworks, like Ruby on Rails, for example, and supports lot of web servers, like WEBrick, Thin, or Puma. Sinatra provides a minimal interface for writing web applications in Ruby, and one of its most compelling features is support for middleware components. These components lie between the application and the web server, and can monitor and manipulate requests and responses.
    For utilizing this Rack feature, Sinatra defines internal DSL for creating web applications. Its philosophy is very simple: Routes are represented by HTTP methods, followed by a route matching a pattern. A Ruby block within which request is processed and the response is formed.

    get '/' do
      'Hello from sinatra'
    end
    

    The route matching pattern can also include a named parameter. When route block is executed, a parameter value is passed to the block through the params variable.

    get '/players/:sport_id' do
      # Parameter value accessible through params[:sport_id]
    end
    

    Matching patterns can use splat operator * which makes parameter values available through params[:splat].

    get '/players/*/:year' do
      # /players/performances/2016
      # Parameters - params['splat'] -> ['performances'], params[:year] -> 2016
    end
    

    This is not the end of Sinatra’s possibilities related to route matching. It can use more complex matching logic through regular expressions, as well as custom matchers.
    Sinatra understands all of the standard HTTP verbs needed for creating a REST API: Get, Post, Put, Patch, Delete, and Options. Route priorities are determined by the order in which they are defined, and the first route that matches a request is the one that serves that request.
    Sinatra applications can be written in two ways; using classical or modular style. The main difference between them is that, with the classical style, we can have only one Sinatra application per Ruby process. Other differences are minor enough that, in most cases, they can be ignored, and the default settings can be used.

    Classical Approach

    Implementing classical application is straightforward. We just have to load Sinatra and implement route handlers:

    require 'sinatra'
    get '/' do
      'Hello from Sinatra'
    end
    

    By saving this code to demo_api_classic.rb file, we can start the application directly by executing the following command:

    ruby demo_api_classic.rb
    

    However, if the application is to be deployed with Rack handlers, like Passenger, it is better to start it with the Rack configuration config.ru file.

    require './demo_api_classic'
    run Sinatra::Application
    

    With the config.ru file in place, the application is started with the following command:

    rackup config.ru
    

    Modular Approach

    Modular Sinatra applications are created by subclassing either Sinatra::Base or Sinatra::Application:

    require 'sinatra'
    class DemoApi < Sinatra::Application
      # Application code
      run! if app_file == $0
    end
    

    The statement beginning with run! is used for starting the application directly, with ruby demo_api.rb, just as with the classical application. On the other hand, if the application is to be deployed with Rack, the handlers content of rackup.ru must be:

    require './demo_api'
    run DemoApi
    

    Sequel

    Sequel is the second tool in this set. In contrast to ActiveRecord, which is part of the Ruby on Rails, Sequel’s dependencies are very small. At the same time, it is quite feature rich and can be used for all kinds of database manipulation tasks. With its simple domain specific language, Sequel relieves the developer from all the problems with maintaining connections, constructing SQL queries, fetching data from (and sending data back to) the database.
    For example, establishing a connection with the database is very simple:

    DB = Sequel.connect(adapter: :postgres, database: 'my_db', host: 'localhost', user: 'db_user')
    

    The connect method returns a database object, in this case, Sequel::Postgres::Database, which can be further used to execute raw SQL.

    DB['select count(*) from players']
    

    Alternatively, to create a new dataset object:

    DB[:players]
    

    Both of these statements create a dataset object, which is a basic Sequel entity.
    One of the most important Sequel dataset features is that it does not execute queries immediately. This makes it possible to store datasets for later use and, in most cases, to chain them.

    users = DB[:players].where(sport: 'tennis')
    

    So, if a dataset does not hit the database immediately, the question is, when does it? Sequel executes SQL on the database when so-called “executable methods” are used. These methods are, to name a few, all, each,map, first, and last.
    Sequel is extensible, and its extensibility is a result of a fundamental architectural decision to build a small core complemented with a plugin system. Features are easily added through plugins which are, actually, Ruby modules. The most important plugin is the Model plugin. It is an empty plugin which does not define any class or instance methods by itself. Instead, it includes other plugins (submodules) which define a class, instance or model dataset methods. The Model plugin enables the use of Sequel as the object-relational-mapping (ORM) tool and is often referred to as the “base plugin”.

    class Player < Sequel::Model
    end
    

    The Sequel model automatically parses the database schema and sets up all necessary accessor methods for all columns. It assumes that table name is plural and is an underscored version of the model name. In case there is a need to work with databases that do not follow this naming convention, the table name can be explicitly set when the model is defined.

    class Player < Sequel::Model(:player)
    end
    

    So, we now have everything we need to start building the back-end API.

    Building the API

    Code Structure

    Contrary to Rails, Sinatra does not impose any project structure. However, since it is always a good practice to organize code for easier maintenance and development, we’ll do it here too, with the following directory structure:

    project root
       |-config
       |-helpers
       |-models
       |-routes
    

    The application configuration will be loaded from the YAML configuration file for the current environment with:

    Sinatra::Application.config_file File.join(File.dirname(__FILE__),
                                               'config',
                                               "#{Sinatra::Application.settings.environment}_config.yml")
    

    By default, Sinatra::Applicationsettings.environment value is development, and it is changed by setting the RACK_ENV environment variable.
    Furthermore, our application must load all files from the other three directories. We can do that easily by running:

    %w{helpers models routes}.each {|dir| Dir.glob("#{dir}/*.rb", &method(:require))}
    

    At first glance, this way of loading might look convenient. However, with this one line of the code, we cannot easily skip files, because it will load all the files from the directories in the array. That’s why we will use a more efficient single-file load approach, which assumes that in each folder we have a manifest file init.rb, which loads all other files from the directory. Also, we will add a target directory to the Ruby load path:

    %w{helpers models routes}.each do |dir|
      $LOAD_PATH << File.expand_path('.', File.join(File.dirname(__FILE__), dir))
      require File.join(dir, 'init')
    end
    

    This approach requires a bit more work because we have to maintain require statements in each init.rb file but, in return, we get more control, and we can easily leave one or more files out by removing them from the manifest init.rb file in the target directory.

    API Authentication

    The first thing we need in each API is authentication. We will implement it as a helper module. Complete authentication logic will be in the helpers/authentication.rb file.

    require 'multi_json'
    module Sinatra
      module Authentication
        def authenticate!
          client_id = request['client_id']
          client_secret = request['client_secret']
          # Authenticate client here
          halt 401, MultiJson.dump({message: "You are not authorized to access this resource"}) unless authenticated?
        end
        def current_client
          @current_client
        end
        def authenticated?
          !current_client.nil?
        end
      end
      helpers Authentication
    end
    

    All we have to do now is to load this file by adding a require statement in the helper manifest file (helpers/init.rb) and to call the authenticate! method in Sinatra’s before hook which will be executed before processing any request.

    before do
      authenticate!
    end
    

    Database

    Next, we have to prepare our database for the application. There are many ways to prepare the database, but since we are using Sequel, it is natural to do it by using migrators. Sequel comes with two migrator types – integer and timestamp based. Each one has its advantages and drawbacks. In our example, we decided to use the Sequel’s timestamp migrator, which requires migration files to be prefixed with a timestamp. The timestamp migrator is very flexible and can accept various timestamp formats, but we will only use the one that consists of year, month, day, hour, minute, and second. Here are our two migration files:

    # db/migrations/20160710094000_sports.rb
    Sequel.migration do
      change do
        create_table(:sports) do
          primary_key :id
          String :name, :null => false
        end
      end
    end
    # db/migrations/20160710094100_players.rb
    Sequel.migration do
      change do
        create_table(:players) do
          primary_key :id
          String :name, :null => false
          foreign_key :sport_id, :sports
        end
      end
    end
    

    We are now ready to create a database with all the tables.

    bundle exec sequel -m db/migrations sqlite://db/development.sqlite3
    

    Finally, we have the model files sport.rb and player.rb in the models directory.

    # models/sport.rb
    class Sport < Sequel::Model
      one_to_many :players
      def to_api
        {
          id: id,
          name: name
        }
      end
    end
    # models/player.rb
    class Player < Sequel::Model
      many_to_one :sport
      def to_api
        {
          id: id,
          name: name,
          sport_id: sport_id
        }
      end
    end
    

    Here we are employing a Sequel way of defining model relationships, where the Sport object has many players and Player can have only one sport. Also, each model defines its to_api method, which returns a hash with attributes that need to be serialized. This is a general approach we can use for various formats. However, if we will only use a JSON format in our API, we could use Ruby’s to_json with only argument to restrict serialization to required attributes, i.e. player.to_json(only: [:id, :name, :sport_i]). Of course, we could also define a BaseModel that inherits from Sequel::Model and defines a default to_api method, from which inherit all models could then inherit.
    Now, we can start implementing the actual API endpoints.

    API Endpoints

    We will keep the definition of all endpoints in files within the routes directory. Since we are using manifest files for loading files, we will group routes by resources (i.e., keep all sports related routes in sports.rb file, all players routes in routes.rb, and so on).

    # routes/sports.rb
    class DemoApi < Sinatra::Application
      get "/sports/?" do
        MultiJson.dump(Sport.all.map { |s| s.to_api })
      end
      get "/sports/:id" do
        sport = Sport.where(id: params[:id]).first
        MultiJson.dump(sport ? sport.to_api : {})
      end
      get "/sports/:id/players/?" do
        sport = Sport.where(id: params[:id]).first
        MultiJson.dump(sport ? sport.players.map { |p| p.to_api } : [])
      end
    end
    # routes/players.rb
    class DemoApi < Sinatra::Application
      get "/players/?" do
        MultiJson.dump(Player.all.map { |p| s.to_api })
      end
      get "/players/:id/?" do
        player = Player.where(id: params[:id]).first
        MultiJson.dump(player ? player.to_api : {})
      end
    end
    

    Nested routes, like the one for getting all the players within one sport /sports/:id/players, can either be defined by placing them together with other routes, or by creating a separate resource file that will contain only the nested routes.
    With designated routes, the application is now ready to accept requests:

    curl -i -XGET 'https://localhost:9292/sports?client_id=<client_id>&client_secret=<client_secret>'
    

    Note that as required by the application’s authentication system defined in helpers/authentication.rb file, we are passing credentials directly in request parameters.

    Conclusion

    The principles demonstrated in this simple example application apply to any API back-end application. It is not based on the model-view-controller (MVC) architecture, yet it keeps a clear separation of responsibilities in a similar way; complete business logic is kept in model files while handling requests is done in Sinatra’s routes methods. Contrary to MVC architecture, where views are used to render responses, this application does that at the same place where it handles requests – in the routes methods. With new helper files, the application can be easily extended to send pagination or, if needed, request limits information back to the user in response headers.
    In the end, we’ve built a complete API with a very simple toolset and without losing any functionality. The limited number of dependencies helps ensure that the application loads and starts much faster, and has a much smaller memory footprint than a Rails based one would have. So, next time you start work on a new API in Ruby, consider using Sinatra and Sequel since they are very powerful tools for such a use case.
    Source: Toptal

  • Hunting Down Memory Issues In Ruby: A Definitive Guide

    I’m sure there are some lucky Ruby developers out there who will never run into issues with memory, but for the rest of us, it’s incredibly challenging to hunt down where memory usage is getting out of hand and fix it. Fortunately, if you’re using a modern Ruby (2.1+), there are some great tools and techniques available for dealing with common issues. It could also be said that memory optimization can be fun and rewarding although I may be alone in that sentiment.
    Hunting Down Memory Issues In Ruby
    As with all forms of optimization, odds are that it will add code complexity, so it’s not worth doing unless there are measurable and significant gains.
    Everything described here is done using the canonical MRI Ruby, version 2.2.4, although other 2.1+ versions should behave similarly.

    It’s Not a Memory Leak!

    When a memory issue is discovered, it’s easy to jump to the conclusion that there’s a memory leak. For example, in a web application, you may see that after you spin up your server, repeated calls to the same endpoint keep driving memory usage up higher with each request. There are certainly cases where legitimate memory leaks happen, but I’d wager they are vastly outnumbered by memory issues with this same appearance that aren’t actually leaks.
    As a (contrived) example, let’s look at a bit of Ruby code that repeatedly builds a big array of hashes and discards it. First, here’s some code that’ll be shared throughout the examples in this post:

    # common.rb
    require "active_record"
    require "active_support/all"
    require "get_process_mem"
    require "sqlite3"
    ActiveRecord::Base.establish_connection(
      adapter: "sqlite3",
      database: "people.sqlite3"
    )
    class Person < ActiveRecord::Base; end
    def print_usage(description)
      mb = GetProcessMem.new.mb
      puts "#{ description } - MEMORY USAGE(MB): #{ mb.round }"
    end
    def print_usage_before_and_after
      print_usage("Before")
      yield
      print_usage("After")
    end
    def random_name
      (0...20).map { (97 + rand(26)).chr }.join
    end
    

    And the array builder:

    # build_arrays.rb
    require_relative "./common"
    ARRAY_SIZE = 1_000_000
    times = ARGV.first.to_i
    print_usage(0)
    (1..times).each do |n|
      foo = []
      ARRAY_SIZE.times { foo << {some: "stuff"} }
      print_usage(n)
    end
    

    The get_process_mem gem is just a convenient way to get the memory being used by the current Ruby process. What we see is the same behavior that was described above, a continual increase in memory usage.

    $ ruby build_arrays.rb 10
    0 - MEMORY USAGE(MB): 17
    1 - MEMORY USAGE(MB): 330
    2 - MEMORY USAGE(MB): 481
    3 - MEMORY USAGE(MB): 492
    4 - MEMORY USAGE(MB): 559
    5 - MEMORY USAGE(MB): 584
    6 - MEMORY USAGE(MB): 588
    7 - MEMORY USAGE(MB): 591
    8 - MEMORY USAGE(MB): 603
    9 - MEMORY USAGE(MB): 613
    10 - MEMORY USAGE(MB): 621
    

    However, if we run more iterations, we’ll eventually plateau.

    $ ruby build_arrays.rb 40
    0 - MEMORY USAGE(MB): 9
    1 - MEMORY USAGE(MB): 323
    ...
    32 - MEMORY USAGE(MB): 700
    33 - MEMORY USAGE(MB): 699
    34 - MEMORY USAGE(MB): 698
    35 - MEMORY USAGE(MB): 698
    36 - MEMORY USAGE(MB): 696
    37 - MEMORY USAGE(MB): 696
    38 - MEMORY USAGE(MB): 696
    39 - MEMORY USAGE(MB): 701
    40 - MEMORY USAGE(MB): 697
    

    Hitting this plateau is the hallmark of not being an actual memory leak, or that the memory leak is so small that it’s not visible compared to the rest of the memory usage. What may not be intuitive is why memory usage continues to grow after the first iteration. After all, it built a big array, but then promptly discarded it and started building a new one of the same size. Can’t it just use the space freed up by the previous array? The answer, which explains our problem, is no. Aside from tuning the garbage collector, you don’t have control over when it runs, and what we’re seeing in the build_arrays.rb example is new memory allocations being made prior to garbage collection of our old, discarded objects.

    Do not panic if you see a sudden rise in the memory usage of your app. Apps can run out of memory for all sorts of reasons – not just memory leaks.

    I should point out that this isn’t some sort of horrible memory management issue specific to Ruby, but is generally applicable to garbage-collected languages. Just to reassure myself of this, I reproduced essentially the same example with Go and saw similar results. However, there are Ruby libraries that make it easy to create this sort of memory issue.

    Divide and Conquer

    So if we need to work with large chunks of data, are we doomed to just throw lots of RAM at our problem? Thankfully, that’s not the case. If we take the build_arrays.rb example and decrease the array size, we’ll see a decrease in the point where memory usage plateaus that’s roughly proportional to the array size.

    This means that if we can break our work into smaller pieces to process and avoid having too many objects existing at one time, we can dramatically reduce the memory footprint. Unfortunately, that often means taking nice, clean code and turning it into more code that does the same thing, just in a more memory-efficient way.

    Isolating Memory Usage Hotspots

    In a real codebase, the source of a memory issue will likely not be as obvious as in the build_arrays.rbexample. Isolating a memory issue before trying to actually dig in and fix it is essential because it’s easy to make incorrect assumptions about what’s causing the problem.

    I generally use two approaches, often in combination, to track down memory issues: leaving the code intact and wrapping a profiler around it, and monitoring memory usage of the process while disabling/enabling different parts of the code I suspect could be problematic. I’ll be using memory_profiler here for profiling, but ruby-prof is another popular option, and derailed_benchmarks has some great Rails-specific capabilities.
    Here’s some code that’ll use a bunch of memory, where it may not be immediately clear which step is pushing up memory usage the most:

    # people.rb
    require_relative "./common"
    def run(number)
      Person.delete_all
      names = number.times.map { random_name }
      names.each do |name|
        Person.create(name: name)
      end
      records = Person.all.to_a
      File.open("people.txt", "w") { |out| out << records.to_json }
    end
    

    Using get_process_mem, we can quickly verify that it does use a lot of memory when there are a lot of Person records being created.

    # before_and_after.rb
    require_relative "./people"
    print_usage_before_and_after do
      run(ARGV.shift.to_i)
    end
    

    Result:

    $ ruby before_and_after.rb 10000
    Before - MEMORY USAGE(MB): 37
    After - MEMORY USAGE(MB): 96
    

    Looking through the code, there are multiple steps that seem like good candidates for using a lot of memory: building a big array of strings, calling #to_a on an Active Record relation to make a big array of Active Record objects (not a great idea, but done for demonstration purposes), and serializing the array of Active Record objects.
    We can then profile this code to see where memory allocations are happening:

    # profile.rb
    require "memory_profiler"
    require_relative "./people"
    report = MemoryProfiler.report do
      run(1000)
    end
    report.pretty_print(to_file: "profile.txt")
    

    Note that the number being fed to run here is 1/10 of the previous example, since the profiler itself uses a lot of memory, and can actually lead to memory exhaustion when profiling code that already causes high memory usage.
    The results file is rather lengthy and includes memory and object allocation and retention at the gem, file, and location levels. There’s a wealth of information to explore, but here are a couple of interesting snippets:

    allocated memory by gem
    -----------------------------------
      17520444  activerecord-4.2.6
       7305511  activesupport-4.2.6
       2551797  activemodel-4.2.6
       2171660  arel-6.0.3
       2002249  sqlite3-1.3.11
    ...
    allocated memory by file
    -----------------------------------
       2840000  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/activ
    e_support/hash_with_indifferent_access.rb
       2006169  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active
    _record/type/time_value.rb
       2001914  /Users/bruz/code/mem_test/people.rb
       1655493  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active
    _record/connection_adapters/sqlite3_adapter.rb
       1628392  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/activ
    e_support/json/encoding.rb
    

    We see the most allocations happening inside Active Record, which would seem to point at either instantiating all the objects in the records array, or serialization with #to_json. Next, we can test our memory usage without the profiler while disabling these suspects. We can’t disable retrieving records and still be able to do the serialization step, so let’s try disabling serialization first.

      # File.open("people.txt", "w") { |out| out << records.to_json }
    

    Result:

    $ ruby before_and_after.rb 10000
    Before: 36 MB
    After: 47 MB
    

    That does indeed seem to be where most of the memory is going, with before/after memory delta dropping 81% by skipping it. We can also see what happens if we stop forcing the big array of records to be created.

      # records = Person.all.to_a
      records = Person.all
      # File.open("people.txt", "w") { |out| out << records.to_json }
    

    Result:

    $ ruby before_and_after.rb 10000
    Before: 36 MB
    After: 40 MB
    

    This reduces memory usage as well, although it’s an order of magnitude less reduction than disabling serialization. So at this point, we know our biggest culprits, and can make a decision about what to optimize based on this data.
    Although the example here was contrived, the approaches are generally applicable. Profiler results may not point you at the exact spot in your code where the problem lies, and can also be misinterpreted, so it’s a good idea to follow up by looking at actual memory usage while turning sections of code on and off. Next, we’ll look at some common cases where memory usage becomes an issue and how to optimize them.

    Deserialization

    A common source of memory issues is deserializing large amounts of data from XML, JSON or some other data serialization format. Using methods like JSON.parse or Active Support’s Hash.from_xml is incredibly convenient, but when the data you’re loading is large, the resulting data structure that’s loaded in memory can be enormous.
    If you have control over the source of the data, you can do things to limit the amount of data you’re receiving, like adding filtering or pagination support. But if it’s an external source or one you can’t control, another option is to use a streaming deserializer. For XML, Ox is one option, and for JSON yajl-ruby appears to operate similarly, although I don’t have much experience with it.

    Just because you have limited memory doesn’t mean you cannot parse large XML or JSON documents safely. Streaming deserializers allow you to incrementally extract whatever you need from these documents and still keep the memory footprint low.

    Here’s an example of parsing a 1.7MB XML file, using Hash#from_xml.

    # parse_with_from_xml.rb
    require_relative "./common"
    print_usage_before_and_after do
      # From https://www.cs.washington.edu/research/xmldatasets/data/mondial/mondial-3.0.xml
      file = File.open(File.expand_path("../mondial-3.0.xml", __FILE__))
      hash = Hash.from_xml(file)["mondial"]["continent"]
      puts hash.map { |c| c["name"] }.join(", ")
    end
    
    $ ruby parse_with_from_xml.rb
    Before - MEMORY USAGE(MB): 37
    Europe, Asia, America, Australia/Oceania, Africa
    After - MEMORY USAGE(MB): 164
    

    111MB for a 1.7MB file! This clearly is not going to scale up well. Here’s the streaming parser version.

    # parse_with_ox.rb
    require_relative "./common"
    require "ox"
    class Handler < ::Ox::Sax
      def initialize(&block)
        @yield_to = block
      end
      def start_element(name)
        case name
        when :continent
          @in_continent = true
        end
      end
      def end_element(name)
        case name
        when :continent
          @yield_to.call(@name) if @name
          @in_continent = false
          @name = nil
        end
      end
      def attr(name, value)
        case name
        when :name
          @name = value if @in_continent
        end
      end
    end
    print_usage_before_and_after do
      # From https://www.cs.washington.edu/research/xmldatasets/data/mondial/mondial-3.0.xml
      file = File.open(File.expand_path("../mondial-3.0.xml", __FILE__))
      continents = []
      handler = Handler.new do |continent|
        continents << continent
      end
      Ox.sax_parse(handler, file)
      puts continents.join(", ")
    end
    
    $ ruby parse_with_ox.rb
    Before - MEMORY USAGE(MB): 37
    Europe, Asia, America, Australia/Oceania, Africa
    After - MEMORY USAGE(MB): 37
    

    This brings us down to a negligible memory increase and should be able to handle vastly larger files. However, the tradeoff is that we now have 28 lines of handler code we didn’t need before, which seems like it’d be error prone, and for production use it should have some tests around it.

    Serialization

    As we saw in the section about isolating memory usage hotspots, serialization can have high memory costs. Here’s the key part of people.rb from earlier.

    # to_json.rb
    require_relative "./common"
    print_usage_before_and_after do
      File.open("people.txt", "w") { |out| out << Person.all.to_json }
    end
    

    Running this with 100,000 records in the database, we get:

    $ ruby to_json.rb
    Before: 36 MB
    After: 505 MB
    

    The issue with calling #to_json here is that it instantiates an object for every record, and then encodes to JSON. Generating the JSON record-by-record so that only one record object would need to exist at a time reduces the memory usage significantly. None of the popular Ruby JSON libraries appear to handle this, but a commonly recommended approach is to build the JSON string manually. There is a json-write-stream gem that provides a nice API for doing this, and converting our example to this looks like:

    # json_stream.rb
    require_relative "./common"
    require "json-write-stream"
    print_usage_before_and_after do
      file = File.open("people.txt", "w")
      JsonWriteStream.from_stream(file) do |writer|
        writer.write_object do |obj_writer|
          obj_writer.write_array("people") do |arr_writer|
            Person.find_each do |people|
              arr_writer.write_element people.as_json
            end
          end
        end
      end
    end
    

    Once again, we see optimization has given us more code, but the result seems worth it:

    $ ruby json_stream.rb
    Before: 36 MB
    After: 56 MB
    

    Being Lazy

    A great feature added to Ruby starting with 2.0 is the ability to make enumerators lazy. This is great for improving memory usage when chaining methods on an enumerator. Let’s start with some code that isn’t lazy:

    # not_lazy.rb
    require_relative "./common"
    number = ARGV.shift.to_i
    print_usage_before_and_after do
      names = number.times
                    .map { random_name }
                    .map { |name| name.capitalize }
                    .map { |name| "#{ name } Jr." }
                    .select { |name| name[0] == "X" }
                    .to_a
    end
    

    Result:

    $ ruby not_lazy.rb 1_000_000
    Before: 36 MB
    After: 546 MB
    


    What happens here is that at each step in the chain, it iterates over every element in the enumerator, producing an array that has the subsequent method in the chain invoked on it, and so forth. Let’s see what happens when we make this lazy, which just requires adding a call to lazy on the enumerator we get from times:

    # lazy.rb
    require_relative "./common"
    number = ARGV.shift.to_i
    print_usage_before_and_after do
      names = number.times.lazy
                    .map { random_name }
                    .map { |name| name.capitalize }
                    .map { |name| "#{ name } Jr." }
                    .select { |name| name[0] == "X" }
                    .to_a
    end
    

    Result:

    $ ruby lazy.rb 1_000_000
    Before: 36 MB
    After: 52 MB
    

    Finally, an example that gives us a huge memory usage win, without adding a lot of extra code! Note that if we didn’t need to accumulate any results at the end, for instance, if each item was saved to the database and could then be forgotten, there would be even less memory usage. To make a lazy enumerable evaluate at the end of the chain, just add a final call to force.
    Another thing to note about the example is that the chain starts with a call to times prior to lazy, which uses very little memory since it just returns an enumerator that will generate an integer each time it’s invoked. So if an enumerable can be used instead of a big array at the beginning of the chain, that will help.

    Keeping everything in huge arrays and maps is convenient, but in real world scenarios, you rarely need to do that.

    One real-world application of building an enumerable to lazily feed into some sort of processing pipeline is processing paginated data. So rather than requesting all the pages and putting them into one big array, they could be exposed through an enumerator that nicely hides all the pagination details. This could look something like:

    def records
      Enumerator.new do |yielder|
        has_more = true
        page = 1
        while has_more
          response = fetch(page)
          response.records.each { |record| yielder << record }
          page += 1
          has_more = response.has_more
        end
      end
    end
    

    Conclusion

    We’ve done some characterization of memory usage in Ruby, and looked at some general tools for tracking down memory issues, as well as some common cases and ways to improve them. The common cases we explored are by no means comprehensive and are highly biased by the sort of issues I personally have encountered. However, the biggest gain may just be getting in the mindset of thinking about how the code will impact memory usage.
    This post originally appeared in the Toptal Engineering blog

  • Hunting Down Memory Issues In Ruby: A Definitive Guide

    I’m sure there are some lucky Ruby developers out there who will never run into issues with memory, but for the rest of us, it’s incredibly challenging to hunt down where memory usage is getting out of hand and fix it. Fortunately, if you’re using a modern Ruby (2.1+), there are some great tools and techniques available for dealing with common issues. It could also be said that memory optimization can be fun and rewarding although I may be alone in that sentiment.
    Hunting Down Memory Issues In Ruby

    If you thought bugs were pesky, wait until you hunt for memory issues.

    As with all forms of optimization, odds are that it will add code complexity, so it’s not worth doing unless there are measurable and significant gains.
    Everything described here is done using the canonical MRI Ruby, version 2.2.4, although other 2.1+ versions should behave similarly.

    It’s Not a Memory Leak!

    When a memory issue is discovered, it’s easy to jump to the conclusion that there’s a memory leak. For example, in a web application, you may see that after you spin up your server, repeated calls to the same endpoint keep driving memory usage up higher with each request. There are certainly cases where legitimate memory leaks happen, but I’d wager they are vastly outnumbered by memory issues with this same appearance that aren’t actually leaks.
    As a (contrived) example, let’s look at a bit of Ruby code that repeatedly builds a big array of hashes and discards it. First, here’s some code that’ll be shared throughout the examples in this post:

    # common.rb
    require "active_record"
    require "active_support/all"
    require "get_process_mem"
    require "sqlite3"
    ActiveRecord::Base.establish_connection(
      adapter: "sqlite3",
      database: "people.sqlite3"
    )
    class Person < ActiveRecord::Base; end
    def print_usage(description)
      mb = GetProcessMem.new.mb
      puts "#{ description } - MEMORY USAGE(MB): #{ mb.round }"
    end
    def print_usage_before_and_after
      print_usage("Before")
      yield
      print_usage("After")
    end
    def random_name
      (0...20).map { (97 + rand(26)).chr }.join
    end
    

    And the array builder:

    # build_arrays.rb
    require_relative "./common"
    ARRAY_SIZE = 1_000_000
    times = ARGV.first.to_i
    print_usage(0)
    (1..times).each do |n|
      foo = []
      ARRAY_SIZE.times { foo << {some: "stuff"} }
      print_usage(n)
    end
    

    The get_process_mem gem is just a convenient way to get the memory being used by the current Ruby process. What we see is the same behavior that was described above, a continual increase in memory usage.

    $ ruby build_arrays.rb 10
    0 - MEMORY USAGE(MB): 17
    1 - MEMORY USAGE(MB): 330
    2 - MEMORY USAGE(MB): 481
    3 - MEMORY USAGE(MB): 492
    4 - MEMORY USAGE(MB): 559
    5 - MEMORY USAGE(MB): 584
    6 - MEMORY USAGE(MB): 588
    7 - MEMORY USAGE(MB): 591
    8 - MEMORY USAGE(MB): 603
    9 - MEMORY USAGE(MB): 613
    10 - MEMORY USAGE(MB): 621
    

    However, if we run more iterations, we’ll eventually plateau.

    $ ruby build_arrays.rb 40
    0 - MEMORY USAGE(MB): 9
    1 - MEMORY USAGE(MB): 323
    ...
    32 - MEMORY USAGE(MB): 700
    33 - MEMORY USAGE(MB): 699
    34 - MEMORY USAGE(MB): 698
    35 - MEMORY USAGE(MB): 698
    36 - MEMORY USAGE(MB): 696
    37 - MEMORY USAGE(MB): 696
    38 - MEMORY USAGE(MB): 696
    39 - MEMORY USAGE(MB): 701
    40 - MEMORY USAGE(MB): 697
    

    Hitting this plateau is the hallmark of not being an actual memory leak, or that the memory leak is so small that it’s not visible compared to the rest of the memory usage. What may not be intuitive is why memory usage continues to grow after the first iteration. After all, it built a big array, but then promptly discarded it and started building a new one of the same size. Can’t it just use the space freed up by the previous array? The answer, which explains our problem, is no. Aside from tuning the garbage collector, you don’t have control over when it runs, and what we’re seeing in the build_arrays.rb example is new memory allocations being made prior to garbage collection of our old, discarded objects.

    Do not panic if you see a sudden rise in the memory usage of your app. Apps can run out of memory for all sorts of reasons – not just memory leaks.

    I should point out that this isn’t some sort of horrible memory management issue specific to Ruby, but is generally applicable to garbage-collected languages. Just to reassure myself of this, I reproduced essentially the same example with Go and saw similar results. However, there are Ruby libraries that make it easy to create this sort of memory issue.

    Divide and Conquer

    So if we need to work with large chunks of data, are we doomed to just throw lots of RAM at our problem? Thankfully, that’s not the case. If we take the build_arrays.rb example and decrease the array size, we’ll see a decrease in the point where memory usage plateaus that’s roughly proportional to the array size.

    This means that if we can break our work into smaller pieces to process and avoid having too many objects existing at one time, we can dramatically reduce the memory footprint. Unfortunately, that often means taking nice, clean code and turning it into more code that does the same thing, just in a more memory-efficient way.

    Isolating Memory Usage Hotspots

    In a real codebase, the source of a memory issue will likely not be as obvious as in the build_arrays.rbexample. Isolating a memory issue before trying to actually dig in and fix it is essential because it’s easy to make incorrect assumptions about what’s causing the problem.

    I generally use two approaches, often in combination, to track down memory issues: leaving the code intact and wrapping a profiler around it, and monitoring memory usage of the process while disabling/enabling different parts of the code I suspect could be problematic. I’ll be using memory_profiler here for profiling, butruby-prof is another popular option, and derailed_benchmarks has some great Rails-specific capabilities.
    Here’s some code that’ll use a bunch of memory, where it may not be immediately clear which step is pushing up memory usage the most:

    # people.rb
    require_relative "./common"
    def run(number)
      Person.delete_all
      names = number.times.map { random_name }
      names.each do |name|
        Person.create(name: name)
      end
      records = Person.all.to_a
      File.open("people.txt", "w") { |out| out << records.to_json }
    end
    

    Using get_process_mem, we can quickly verify that it does use a lot of memory when there are a lot of Person records being created.

    # before_and_after.rb
    require_relative "./people"
    print_usage_before_and_after do
      run(ARGV.shift.to_i)
    end
    

    Result:

    $ ruby before_and_after.rb 10000
    Before - MEMORY USAGE(MB): 37
    After - MEMORY USAGE(MB): 96
    

    Looking through the code, there are multiple steps that seem like good candidates for using a lot of memory: building a big array of strings, calling #to_a on an Active Record relation to make a big array of Active Record objects (not a great idea, but done for demonstration purposes), and serializing the array of Active Record objects.
    We can then profile this code to see where memory allocations are happening:

    # profile.rb
    require "memory_profiler"
    require_relative "./people"
    report = MemoryProfiler.report do
      run(1000)
    end
    report.pretty_print(to_file: "profile.txt")
    

    Note that the number being fed to run here is 1/10 of the previous example, since the profiler itself uses a lot of memory, and can actually lead to memory exhaustion when profiling code that already causes high memory usage.
    The results file is rather lengthy and includes memory and object allocation and retention at the gem, file, and location levels. There’s a wealth of information to explore, but here are a couple of interesting snippets:

    allocated memory by gem
    -----------------------------------
      17520444  activerecord-4.2.6
       7305511  activesupport-4.2.6
       2551797  activemodel-4.2.6
       2171660  arel-6.0.3
       2002249  sqlite3-1.3.11
    ...
    allocated memory by file
    -----------------------------------
       2840000  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/activ
    e_support/hash_with_indifferent_access.rb
       2006169  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active
    _record/type/time_value.rb
       2001914  /Users/bruz/code/mem_test/people.rb
       1655493  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activerecord-4.2.6/lib/active
    _record/connection_adapters/sqlite3_adapter.rb
       1628392  /Users/bruz/.rvm/gems/ruby-2.2.4/gems/activesupport-4.2.6/lib/activ
    e_support/json/encoding.rb
    

    We see the most allocations happening inside Active Record, which would seem to point at either instantiating all the objects in the records array, or serialization with #to_json. Next, we can test our memory usage without the profiler while disabling these suspects. We can’t disable retrieving records and still be able to do the serialization step, so let’s try disabling serialization first.

      # File.open("people.txt", "w") { |out| out << records.to_json }
    

    Result:

    $ ruby before_and_after.rb 10000
    Before: 36 MB
    After: 47 MB
    

    That does indeed seem to be where most of the memory is going, with before/after memory delta dropping 81% by skipping it. We can also see what happens if we stop forcing the big array of records to be created.

      # records = Person.all.to_a
      records = Person.all
      # File.open("people.txt", "w") { |out| out << records.to_json }
    

    Result:

    $ ruby before_and_after.rb 10000
    Before: 36 MB
    After: 40 MB
    

    This reduces memory usage as well, although it’s an order of magnitude less reduction than disabling serialization. So at this point, we know our biggest culprits, and can make a decision about what to optimize based on this data.
    Although the example here was contrived, the approaches are generally applicable. Profiler results may not point you at the exact spot in your code where the problem lies, and can also be misinterpreted, so it’s a good idea to follow up by looking at actual memory usage while turning sections of code on and off. Next, we’ll look at some common cases where memory usage becomes an issue and how to optimize them.

    Deserialization

    A common source of memory issues is deserializing large amounts of data from XML, JSON or some other data serialization format. Using methods like JSON.parse or Active Support’s Hash.from_xml is incredibly convenient, but when the data you’re loading is large, the resulting data structure that’s loaded in memory can be enormous.
    If you have control over the source of the data, you can do things to limit the amount of data you’re receiving, like adding filtering or pagination support. But if it’s an external source or one you can’t control, another option is to use a streaming deserializer. For XML, Ox is one option, and for JSON yajl-ruby appears to operate similarly, although I don’t have much experience with it.

    Just because you have limited memory doesn’t mean you cannot parse large XML or JSON documents safely. Streaming deserializers allow you to incrementally extract whatever you need from these documents and still keep the memory footprint low.

    Here’s an example of parsing a 1.7MB XML file, using Hash#from_xml.

    # parse_with_from_xml.rb
    require_relative "./common"
    print_usage_before_and_after do
      # From https://www.cs.washington.edu/research/xmldatasets/data/mondial/mondial-3.0.xml
      file = File.open(File.expand_path("../mondial-3.0.xml", __FILE__))
      hash = Hash.from_xml(file)["mondial"]["continent"]
      puts hash.map { |c| c["name"] }.join(", ")
    end
    
    $ ruby parse_with_from_xml.rb
    Before - MEMORY USAGE(MB): 37
    Europe, Asia, America, Australia/Oceania, Africa
    After - MEMORY USAGE(MB): 164
    

    111MB for a 1.7MB file! This clearly is not going to scale up well. Here’s the streaming parser version.

    # parse_with_ox.rb
    require_relative "./common"
    require "ox"
    class Handler < ::Ox::Sax
      def initialize(&block)
        @yield_to = block
      end
      def start_element(name)
        case name
        when :continent
          @in_continent = true
        end
      end
      def end_element(name)
        case name
        when :continent
          @yield_to.call(@name) if @name
          @in_continent = false
          @name = nil
        end
      end
      def attr(name, value)
        case name
        when :name
          @name = value if @in_continent
        end
      end
    end
    print_usage_before_and_after do
      # From https://www.cs.washington.edu/research/xmldatasets/data/mondial/mondial-3.0.xml
      file = File.open(File.expand_path("../mondial-3.0.xml", __FILE__))
      continents = []
      handler = Handler.new do |continent|
        continents << continent
      end
      Ox.sax_parse(handler, file)
      puts continents.join(", ")
    end
    
    $ ruby parse_with_ox.rb
    Before - MEMORY USAGE(MB): 37
    Europe, Asia, America, Australia/Oceania, Africa
    After - MEMORY USAGE(MB): 37
    

    This brings us down to a negligible memory increase and should be able to handle vastly larger files. However, the tradeoff is that we now have 28 lines of handler code we didn’t need before, which seems like it’d be error prone, and for production use it should have some tests around it.

    Serialization

    As we saw in the section about isolating memory usage hotspots, serialization can have high memory costs. Here’s the key part of people.rb from earlier.

    # to_json.rb
    require_relative "./common"
    print_usage_before_and_after do
      File.open("people.txt", "w") { |out| out << Person.all.to_json }
    end
    

    Running this with 100,000 records in the database, we get:

    $ ruby to_json.rb
    Before: 36 MB
    After: 505 MB
    

    The issue with calling #to_json here is that it instantiates an object for every record, and then encodes to JSON. Generating the JSON record-by-record so that only one record object would need to exist at a time reduces the memory usage significantly. None of the popular Ruby JSON libraries appear to handle this, but a commonly recommended approach is to build the JSON string manually. There is a json-write-stream gem that provides a nice API for doing this, and converting our example to this looks like:

    # json_stream.rb
    require_relative "./common"
    require "json-write-stream"
    print_usage_before_and_after do
      file = File.open("people.txt", "w")
      JsonWriteStream.from_stream(file) do |writer|
        writer.write_object do |obj_writer|
          obj_writer.write_array("people") do |arr_writer|
            Person.find_each do |people|
              arr_writer.write_element people.as_json
            end
          end
        end
      end
    end
    

    Once again, we see optimization has given us more code, but the result seems worth it:

    $ ruby json_stream.rb
    Before: 36 MB
    After: 56 MB
    

    Being Lazy

    A great feature added to Ruby starting with 2.0 is the ability to make enumerators lazy. This is great for improving memory usage when chaining methods on an enumerator. Let’s start with some code that isn’t lazy:

    # not_lazy.rb
    require_relative "./common"
    number = ARGV.shift.to_i
    print_usage_before_and_after do
      names = number.times
                    .map { random_name }
                    .map { |name| name.capitalize }
                    .map { |name| "#{ name } Jr." }
                    .select { |name| name[0] == "X" }
                    .to_a
    end
    

    Result:

    $ ruby not_lazy.rb 1_000_000
    Before: 36 MB
    After: 546 MB
    


    What happens here is that at each step in the chain, it iterates over every element in the enumerator, producing an array that has the subsequent method in the chain invoked on it, and so forth. Let’s see what happens when we make this lazy, which just requires adding a call to lazy on the enumerator we get from times:

    # lazy.rb
    require_relative "./common"
    number = ARGV.shift.to_i
    print_usage_before_and_after do
      names = number.times.lazy
                    .map { random_name }
                    .map { |name| name.capitalize }
                    .map { |name| "#{ name } Jr." }
                    .select { |name| name[0] == "X" }
                    .to_a
    end
    

    Result:

    $ ruby lazy.rb 1_000_000
    Before: 36 MB
    After: 52 MB
    

    Finally, an example that gives us a huge memory usage win, without adding a lot of extra code! Note that if we didn’t need to accumulate any results at the end, for instance, if each item was saved to the database and could then be forgotten, there would be even less memory usage. To make a lazy enumerable evaluate at the end of the chain, just add a final call to force.
    Another thing to note about the example is that the chain starts with a call to times prior to lazy, which uses very little memory since it just returns an enumerator that will generate an integer each time it’s invoked. So if an enumerable can be used instead of a big array at the beginning of the chain, that will help.

    Keeping everything in huge arrays and maps is convenient, but in real world scenarios, you rarely need to do that.

    One real-world application of building an enumerable to lazily feed into some sort of processing pipeline is processing paginated data. So rather than requesting all the pages and putting them into one big array, they could be exposed through an enumerator that nicely hides all the pagination details. This could look something like:

    def records
      Enumerator.new do |yielder|
        has_more = true
        page = 1
        while has_more
          response = fetch(page)
          response.records.each { |record| yielder record }
          page += 1
          has_more = response.has_more
        end
      end
    end
    

    Conclusion

    We’ve done some characterization of memory usage in Ruby, and looked at some general tools for tracking down memory issues, as well as some common cases and ways to improve them. The common cases we explored are by no means comprehensive and are highly biased by the sort of issues I personally have encountered. However, the biggest gain may just be getting in the mindset of thinking about how the code will impact memory usage.
    This article was written by Bruz Marzolf, a Toptal Ruby developer.

  • Grape Gem Tutorial: How To Build A REST-Like API In Ruby

    As Ruby On Rails developers, we often need to extend our applications with API endpoints to support JavaScript-heavy Rich Internet clients or native iPhone and Android apps. There are also some cases where the application’s sole purpose is to serve the iPhone/Android apps via a JSON API.
    In this tutorial, I demonstrate how to use Grape – a REST-like API micro-framework for Ruby – to build backend support in Rails for a JSON API. Grape is designed to run as a mountable rack engine tocomplement our web applications, without interfering with them.

    Use Case

    The use case we will focus on for this tutorial is an application capable of capturing and reviewing pair programming sessions. The application itself will be written for iOS in ObjectiveC and will need to communicate with a backend service for storing and retrieving the data. Our focus in this tutorial is on creation of a robust and secure backend service that supports a JSON API.
    The API will support methods for:

    • Logging in to the system
    • Querying pair programming session reviews

    NOTE: In addition to providing the ability to query pair programming session reviews, the real API would also need to provide a facility for submitting pair programming reviews for inclusion in the database. Since supporting that via the API is beyond the scope of this tutorial, we will simply assume that the database has been populated with a sample set of pair programming reviews.
    Key technical requirements include:

    • Every API call must return valid JSON
    • Every failed API call must be recorded with adequate context and information to subsequently be reproducible, and debugged if necessary

    Also, since our application will need to serve external clients, we will need to concern ourselves with security. Toward that end:

    • Each request should be restricted to a small subset of developers we track
    • All requests (other than login/signup) need to be authenticated

    Test Driven Development And RSpec

    We will use Test Driven Development (TDD) as our software development approach to help ensure the deterministic behavior of our API.
    For testing purposes we will use RSpec, a well known testing framework in the RubyOnRails community. I will therefore refer in this article to “specs” rather than “tests”.
    A comprehensive testing methodology consists of both “positive” and “negative” tests. Negative specs will specify, for example, how the API endpoint behaves if some parameters are missing or incorrect. Positive specs cover cases where the API is invoked correctly.

    Getting Started

    Let’s put down the foundation for our backend API. First, we need to create a new rails application:

    rails new toptal_grape_blog
    

    Next, we’ll install RSpec by adding rspec-rails into our gemfile:

    group :development, :test do
      gem 'rspec-rails', '~> 3.2'
    end
    

    Then from our command line we need to run:

    rails generate rspec:install
    

    We can also leverage some existing open source software for our testing framework. Specifically:

    Step 1: Add these into our gemfile:

    ...
    gem 'devise'
    ...
    group :development, :test do
    ...
      gem 'factory_girl_rails', '~> 4.5'
    ...
    end
    

    Step 2: Generate a user model, initialize the devise gem, and add it to the user model (this enables the user class to be used for authentication).

    rails g model user
    rails generate devise:install
    rails generate devise user
    

    Step 3: Include the factory_girl syntax method in our rails_helper.rb file in order to use the abbreviated version of user creation in our specs:

    RSpec.configure do |config|
      config.include FactoryGirl::Syntax::Methods
    

    Step 4: Add the grape gem to our DSL and install it:

    gem 'grape'
    bundle
    

    User Login Use Case And Spec

    Our backend will need to support a basic login capability. Let’s create the skeleton for our login_spec, assuming that a valid login request consists of a registered email address and password pair:

    require 'rails_helper'
    describe '/api/login' do
      context 'negative tests' do
        context 'missing params' do
          context 'password' do
          end
          context 'email' do
          end
        end
        context 'invalid params' do
          context 'incorrect password' do
          end
          context 'with a non-existent login' do
          end
        end
      end
      context 'positive tests' do
        context 'valid params' do
        end
      end
    end
    

    If either of the parameters is missing, the client should receive an HTTP return status code of 400 (i.e., Bad Request), along with an error message of ‘email is missing’ or ’password is missing’.
    For our test, we will create a valid user and set the user’s email and password as original parameters for this test suite. Then we will customize this parameter hash for every specific spec by either omitting the password/email or overriding it.
    Let’s create the user and the parameter hash at the beginning of the spec. We will put this code after the describe block:

    describe '/api/login' do
      let(:email) { user.email }
      let(:password) { user.password }
      let!(:user) { create :user }
      let(:original_params) { { email: email, password: password } }
      let(:params) { original_params }
      ...
    

    We can then extend our ‘missing params’/’password’ context as follows:

    let(:params) { original_params.except(:password) }
    it_behaves_like '400'
    it_behaves_like 'json result'
    it_behaves_like 'contains error msg', 'password is missing'
    

    But instead of repeating the expectations across the ‘email’ and ‘password’ contexts, we can use the same shared examples as expectations. For this, we need to uncomment this line in our rails_helper.rb file:

    Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
    

    We then need to add the 3 RSpec shared examples into spec/support/shared.rb:

    RSpec.shared_examples 'json result' do
      specify 'returns JSON' do
        api_call params
        expect { JSON.parse(response.body) }.not_to raise_error
      end
    end
    RSpec.shared_examples '400' do
      specify 'returns 400' do
        api_call params
        expect(response.status).to eq(400)
      end
    end
    RSpec.shared_examples 'contains error msg' do |msg|
      specify "error msg is #{msg}" do
        api_call params
        json = JSON.parse(response.body)
        expect(json['error_msg']).to eq(msg)
      end
    end
    

    These shared examples are calling the api_call method which enables us to define the API endpoint only once in our spec (in keeping with the DRY principle). We define this method as follows:

    describe '/api/login' do
    ...
      def api_call *params
        post "/api/login", *params
      end
    ...
    

    We will also need to customize the factory for our user:

    FactoryGirl.define do
      factory :user do
        password "Passw0rd"
        password_confirmation { |u| u.password }
        sequence(:email) { |n| "test#{n}@example.com" }
      end
    end
    

    And finally, before running our specs we need to run our migrations:

    rake db:migrate
    

    Bear in mind, though, that the specs will still fail at this point, since we haven’t yet implemented our API endpoint. That’s next.

    Implementing The Login API Endpoint

    For starters, we’ll write an empty skeleton for our login API (app/api/login.rb):

    class Login < Grape::API
      format :json
      desc 'End-points for the Login'
      namespace :login do
        desc 'Login via email and password'
        params do
          requires :email, type: String, desc: 'email'
          requires :password, type: String, desc: 'password'
        end
        post do
        end
      end
    end
    

    Next, we’ll write an aggregator class which aggregates the API endpoints (app/api/api.rb):

    class API < Grape::API
      prefix 'api'
      mount Login
    end
    

    OK, now we can mount our API in the routes:

    Rails.application.routes.draw do
    ...
      mount API => '/'
    ...
    end
    

    Now let’s add the code to check for the missing parameters. We can add that code to api.rb by rescuing from Grape::Exceptions::ValidationErrors.

    rescue_from Grape::Exceptions::ValidationErrors do |e|
      rack_response({
        status: e.status,
        error_msg: e.message,
      }.to_json, 400)
    end
    

    For the invalid password, we will check if the http response code is 401 which means unauthorized access. Let’s add this to the ‘incorrect password’ context:

    let(:params) { original_params.merge(password: 'invalid') }
    it_behaves_like '401'
    it_behaves_like 'json result'
    it_behaves_like 'contains error msg', 'Bad Authentication Parameters'
    

    The same logic is then added to the ‘with a non-existent login’ context as well.
    We then implement the logic which handles the invalid authentication attempts into our login.rb as follows:

    post do
      user = User.find_by_email params[:email]
      if user.present? && user.valid_password?(params[:password])
      else
        error_msg = 'Bad Authentication Parameters'
        error!({ 'error_msg' => error_msg }, 401)
      end
    end
    

    At this point all of the negative specs for the login api will behave properly, but we still need to support the positive specs for our login api. Our positive spec will expect the endpoint to return an HTTP response code of 200 (i.e., success) with valid JSON and a valid token:

    it_behaves_like '200'
    it_behaves_like 'json result'
    specify 'returns the token as part of the response' do
      api_call params
      expect(JSON.parse(response.body)['token']).to be_present
    end
    

    Let’s also add the expectation for the response code 200 to spec/support/shared.rb:

    RSpec.shared_examples '200' do
      specify 'returns 200' do
        api_call params
        expect(response.status).to eq(200)
      end
    end
    

    In case of successful login we are going to return the first valid authentication_token together with the user’s email in this format:

    {‘email’:<the_email_of_the_user>, ‘token’:<the users first valid token>}
    

    If there is no such token yet then we will create one for the current user:

    ...
    if user.present? && user.valid_password?(params[:password])
      token = user.authentication_tokens.valid.first || AuthenticationToken.generate(user)
      status 200
    else
    ...
    

    In order for this to work, we will need an AuthenticationToken class which belongs to the user. We will generate this model, then run the corresponding migration:

    rails g model authentication_token token user:references expires_at:datetime
    rake db:migrate
    

    We also need to add the corresponding association to our user model:

    class User < ActiveRecord::Base
      has_many :authentication_tokens
    end
    

    Then we will add the valid scope to the AuthenticationToken class:

    class AuthenticationToken < ActiveRecord::Base
      belongs_to :user
      validates :token, presence: true
      scope :valid,  -> { where{ (expires_at == nil) | (expires_at > Time.zone.now) } }
    end
    

    Note that we used Ruby syntax in the where statement. This is enabled by our use of the squeel gem which enables support for Ruby syntax in activerecord queries.
    For a validated user, we are going to create an entity that we’ll refer to as the “user with token entity”, leveraging the features of the grape-entity gem.
    Let’s write the spec for our entity and put it in the user_with_token_entity_spec.rb file:

    require 'rails_helper'
    describe Entities::UserWithTokenEntity do
      describe 'fields' do
        subject(:subject) { Entities::UserWithTokenEntity }
        specify { expect(subject).to represent(:email)}
        let!(:token) { create :authentication_token }
        specify 'presents the first available token' do
          json = Entities::UserWithTokenEntity.new(token.user).as_json
          expect(json[:token]).to be_present
        end
      end
    end
    

    Next let’s add the entities to user_entity.rb:

    module Entities
      class UserEntity < Grape::Entity
        expose :email
      end
    end
    

    And finally, add another class to user_with_token_entity.rb:

    module Entities
      class UserWithTokenEntity < UserEntity
        expose :token do |user, options|
          user.authentication_tokens.valid.first.token
        end
      end
    end
    

    Since we don’t want tokens to remain valid indefinitely, we have them expire after one day:

    FactoryGirl.define do
      factory :authentication_token do
        token "MyString"
        expires_at 1.day.from_now
        user
      end
    end
    

    With this all done, we can now return the expected JSON format with our newly written UserWithTokenEntity:

    ...
    user = User.find_by_email params[:email]
    if user.present? && user.valid_password?(params[:password])
      token = user.authentication_tokens.valid.first || AuthenticationToken.generate(user)
      status 200
      present token.user, with: Entities::UserWithTokenEntity
    else
    ...
    

    Cool. Now all of our specs are passing and the functional requirements of the basic login api endpoint are supported.

    Pair Programming Session Review API Endpoint: Getting Started

    Our backend will need to allow authorized developers who have logged in to query pair programming session reviews.
    Our new API endpoint will be mounted to /api/pair_programming_session and will return the reviews belonging to a project. Let’s begin by writing a basic skeleton for this spec:

    require 'rails_helper'
    describe '/api' do
      describe '/pair_programming_session' do
        def api_call *params
          get '/api/pair_programming_sessions', *params
        end
        context 'invalid params' do
        end
        context 'valid params' do
        end
      end
    end
    

    We will write a corresponding empty API endpoint (app/api/pair_programming_sessions.rb) as well:

    class PairProgrammingSessions < Grape::API
      format :json
      desc 'End-points for the PairProgrammingSessions'
      namespace :pair_programming_sessions do
        desc 'Retrieve the pairprogramming sessions'
        params do
          requires :token, type: String, desc: 'email'
        end
        get do
        end
      end
    end
    

    Then let’s mount our new api (app/api/api.rb):

    ...
      mount Login
      mount PairProgrammingSessions
    end
    

    Let’s expand the spec, and the API endpoint, against the requirements one by one.

    Pair Programming Session Review API Endpoint: Validation

    One of our most important non-functional security requirements was to restrict API access to a small subset of developers we track, so let’s specify that:

    ...
    def api_call *params
      get '/api/pair_programming_sessions', *params
    end
    let(:token) { create :authentication_token }
    let(:original_params) { { token: token.token} }
    let(:params) { original_params }
    it_behaves_like 'restricted for developers'
    context 'invalid params' do
    ...
    

    Then we will create a shared_example in our shared.rb to confirm that the request is coming from one of our registered developers:

    RSpec.shared_examples 'restricted for developers' do
      context 'without developer key' do
        specify 'should be an unauthorized call' do
          api_call params
          expect(response.status).to eq(401)
        end
        specify 'error code is 1001' do
          api_call params
          json = JSON.parse(response.body)
          expect(json['error_code']).to eq(ErrorCodes::DEVELOPER_KEY_MISSING)
        end
      end
    end
    

    We will also need to create an ErrorCodes class (in app/models/error_codes.rb):

    module ErrorCodes
      DEVELOPER_KEY_MISSING = 1001
    end
    

    Since we expect our API to expand in the future, we are going to implement an authorization_helper which can be reused across all API endpoints in the application to restrict access to registered developers only:

    class PairProgrammingSessions < Grape::API
      helpers ApiHelpers::AuthenticationHelper
      before { restrict_access_to_developers }
    

    We are going to define the method restrict_access_to_developers in the ApiHelpers::AuthenticationHerlpermodule (app/api/api_helpers/authentication_helper.rb). This method will simply check if the key Authorization under the headers contains a valid ApiKey. (Every developer wanting access to the API will require a valid ApiKey. This could either be provided by a system administrator or via some automated registration process, but that mechanism is beyond the scope of this article.)

    module ApiHelpers
      module AuthenticationHelper
        def restrict_access_to_developers
          header_token = headers['Authorization']
          key = ApiKey.where{ token == my{ header_token } }
          Rails.logger.info "API call: #{headers}tWith params: #{params.inspect}" if ENV['DEBUG']
          if key.blank?
            error_code = ErrorCodes::DEVELOPER_KEY_MISSING
            error_msg = 'please aquire a developer key'
            error!({ :error_msg => error_msg, :error_code => error_code }, 401)
            # LogAudit.new({env:env}).execute
          end
        end
      end
    end
    

    We then need to generate the ApiKey model and run the migrations: rails g model api_key token rake db:migrate
    With this done, in our spec/api/pair_programming_spec.rb we can check if the user is authenticated:

    ...
    it_behaves_like 'restricted for developers'
    it_behaves_like 'unauthenticated'
    ...
    

    Let’s also define an unauthenticated shared example which can be reused across all specs (spec/support/shared.rb):

    RSpec.shared_examples 'unauthenticated' do
      context 'unauthenticated' do
        specify 'returns 401 without token' do
          api_call params.except(:token), developer_header
          expect(response.status).to eq(401)
        end
        specify 'returns JSON' do
          api_call params.except(:token), developer_header
          json = JSON.parse(response.body)
        end
      end
    end
    

    This shared example needs the token in the developer header so let’s add that to our spec (spec/api/pair_programming_spec.rb):

    ...
    describe '/api' do
      let(:api_key) { create :api_key }
      let(:developer_header) { {'Authorization' => api_key.token} }
    ...
    

    Now, in our app/api/pair_programming_session.rb, let’s attempt to authenticate the user:

    ...
    class PairProgrammingSessions < Grape::API
      helpers ApiHelpers::AuthenticationHelper
      before { restrict_access_to_developers }
      before { authenticate! }
    ...
    

    Let’s implement the authenticate! method in the AuthenticationHelper (app/api/api_helpers/authentication_helper.rb):

    ...
    module ApiHelpers
      module AuthenticationHelper
        TOKEN_PARAM_NAME = :token
        def token_value_from_request(token_param = TOKEN_PARAM_NAME)
          params[token_param]
        end
        def current_user
          token = AuthenticationToken.find_by_token(token_value_from_request)
          return nil unless token.present?
          @current_user ||= token.user
        end
        def signed_in?
          !!current_user
        end
        def authenticate!
          unless signed_in?
            AuditLog.create data: 'unauthenticated user access'
            error!({ :error_msg => "authentication_error", :error_code => ErrorCodes::BAD_AUTHENTICATION_PARAMS }, 401)
          end
        end
    ...
    

    (Note that we need to add the error code BAD_AUTHENTICATION_PARAMS to our ErrorCodes class.)
    Next, let’s spec what happens if the developer calls the API with an invalid token. In that case the return code will be 401 signaling an ‘unauthorized access’. The result should be JSON and an auditable should be created. So we add this to spec/api/pair_programming_spec.rb:

    ...
    context 'invalid params' do
      context 'incorrect token' do
        let(:params) { original_params.merge(token: 'invalid') }
        it_behaves_like '401'
        it_behaves_like 'json result'
        it_behaves_like 'auditable created'
        it_behaves_like 'contains error msg', 'authentication_error'
        it_behaves_like 'contains error code', ErrorCodes::BAD_AUTHENTICATION_PARAMS
      end
    end
    ...
    

    We will add the “auditable created”, “contains error code”, and “contains error msg” shared examples to spec/support/shared.rb:

    ...
    RSpec.shared_examples 'contains error code' do |code|
      specify "error code is #{code}" do
        api_call params, developer_header
        json = JSON.parse(response.body)
        expect(json['error_code']).to eq(code)
      end
    end
    RSpec.shared_examples 'contains error msg' do |msg|
      specify "error msg is #{msg}" do
        api_call params, developer_header
        json = JSON.parse(response.body)
        expect(json['error_msg']).to eq(msg)
      end
    end
    RSpec.shared_examples 'auditable created' do
      specify 'creates an api call audit' do
        expect do
          api_call params, developer_header
        end.to change{ AuditLog.count }.by(1)
      end
    end
    ...
    

    We also need to create an audit_log model:

    rails g model audit_log backtrace data user:references
    rake db:migrate
    

    Pair Programming Session Review API Endpoint: Returning Results

    For an authenticated and authorized user, a call to this API endpoint should return a set of pair programming session reviews grouped by project. Let’s modify our spec/api/pair_programming_spec.rb accordingly:

    ...
    context 'valid params' do
    it_behaves_like '200'
    it_behaves_like 'json result'
    end
    ...
    

    This specifies that a request submitted with valid api_key and valid parameters returns an HTTP code of 200 (i.e., success) and that the result is returned in the form of valid JSON.
    We are going to query and then return in JSON format those pair programming sessions where any of the participant is the current user (app/api/pair_programming_sessions.rb):

    ...
    get do
    sessions = PairProgrammingSession.where{(host_user == my{current_user}) | (visitor_user == my{current_user})}
    sessions = sessions.includes(:project, :host_user, :visitor_user, reviews: [:code_samples, :user] )
    present sessions, with: Entities::PairProgrammingSessionsEntity
    end
    ...
    

    The pair programming sessions are modeled as follows in the database:

    • 1-to-many relationship between projects and pair programming sessions
    • 1-to-many relationship between pair programming sessions and reviews
    • 1-to-many relationship between reviews and code samples

    Let’s generate the models accordingly and then run the migrations:

    rails g model project name
    rails g model pair_programming_session project:references host_user:references visitor_user:references
    rails g model review pair_programming_session:references user:references comment
    rails g model code_sample review:references code:text
    rake db:migrate
    

    Then we need to modify our PairProgrammingSession and Review classes to contain the has_manyassociations:

    class Review < ActiveRecord::Base
      belongs_to :pair_programming_session
      belongs_to :user
      has_many :code_samples
    end
    class PairProgrammingSession < ActiveRecord::Base
      belongs_to :project
      belongs_to :host_user, class_name: :User
      belongs_to :visitor_user, class_name: 'User'
      has_many :reviews
    end
    

    NOTE: In normal circumstances, I would generate these classes by writing specs for them first ,but since that is beyond the scope of this article, I will skip that step.
    Now we need to write those classes which are going to transform our models to their JSON representations (referred to as grape-entities in grape terminology). For simplicity, we will use 1-to-1 mapping between the models and grape-entities.
    We begin by exposing the code field from the CodeSampleEntity (in api/entities/code_sample_entity.rb):

    module Entities
      class CodeSampleEntity < Grape::Entity
        expose :code
      end
    end
    

    Then we expose the user and associated code_samples by reusing the already defined UserEntity and the CodeSampleEntity:

    module Entities
      class ReviewEntity < Grape::Entity
        expose :user, using: UserEntity
        expose :code_samples, using: CodeSampleEntity
      end
    end
    

    We also expose the name field from the ProjectEntity:

    module Entities
      class ProjectEntity < Grape::Entity
        expose :name
      end
    end
    

    Finally, we assemble the entity into a new PairProgrammingSessionsEntity where we expose the project, the host_user, the visitor_user and the reviews:

    module Entities
      class PairProgrammingSessionsEntity < Grape::Entity
        expose :project, using: ProjectEntity
        expose :host_user, using: UserEntity
        expose :visitor_user, using: UserEntity
        expose :reviews, using: ReviewEntity
      end
    end
    

    And with that, our API is fully implemented!

    Generating Test Data

    For testing purposes, we’ll create some sample data in db/seeds.rb. This file should contain all the record creation needed to seed the database with its default values. The data can then be loaded with rake db:seed(or created with the db when db:setup is invoked). Here’s an example of what this could include:

    user_1 = User.create email: '[email protected]', password: 'password', password_confirmation: 'password'
    user_2 = User.create email: '[email protected]', password: 'password', password_confirmation: 'password'
    user_3 = User.create email: '[email protected]', password: 'password', password_confirmation: 'password'
    ApiKey.create token: '12345654321'
    project_1 = Project.create name: 'Time Sheets'
    project_2 = Project.create name: 'Toptal Blog'
    project_3 = Project.create name: 'Hobby Project'
    session_1 = PairProgrammingSession.create project: project_1, host_user: user_1, visitor_user: user_2
    session_2 = PairProgrammingSession.create project: project_2, host_user: user_1, visitor_user: user_3
    session_3 = PairProgrammingSession.create project: project_3, host_user: user_2, visitor_user: user_3
    review_1 = session_1.reviews.create user: user_1, comment: 'Please DRY a bit your code'
    review_2 = session_1.reviews.create user: user_1, comment: 'Please DRY a bit your specs'
    review_3 = session_2.reviews.create user: user_1, comment: 'Please DRY your view templates'
    review_4 = session_2.reviews.create user: user_1, comment: 'Please clean your N+1 queries'
    review_1.code_samples.create code: 'Lorem Ipsum'
    review_1.code_samples.create code: 'Do not abuse the single responsibility principle'
    review_2.code_samples.create code: 'Use some shared examples'
    review_2.code_samples.create code: 'Use at the beginning of specs'
    

    Now our application is ready for use and we can launch our rails server.

    Testing the API

    We will use Swagger to do some manual browser-based testing of our API. A few setup steps are required for us to be able to make use of Swagger though.
    First, we need to add a couple of gems to our gemfile:

    ...
    gem 'grape-swagger'
    gem 'grape-swagger-ui'
    ...
    

    We then run bundle to install these gems.
    We also need to add these to assets to our assets pipeline (in config/initializers/assets.rb):

    Rails.application.config.assets.precompile += %w( swagger_ui.js )
    Rails.application.config.assets.precompile += %w( swagger_ui.css )
    

    Finally, in app/api/api.rb we need to mount the swagger generator:

    ...
      add_swagger_documentation
    end
    ...
    

    Now we can take advantage of Swagger’s nice UI to explore our API by simply going to https://localhost:3000/api/swagger.
    Swagger presents our API endpoints in a nicely explorable way. If we click on an endpoint, Swagger lists its operations. If we click on an operation, Swagger shows its required and optional parameters and their data types.
    One remaining detail though before we proceed: Since we restricted use of the API developers with a valid api_key, we won’t be able to access the API endpoint directly from the browser because the server will require a valid api_key in the HTTP header. We can accomplish this for testing purposes in Google Chrome by making use of the Modify Headers for Google Chrome plugin. This plugin will enable us to edit the HTTP header and add in a valid api_key (we’ll use the dummy api_key of 12345654321 that we included in our database seed file).
    OK, now we’re ready to test!
    In order to call the pair_programming_sessions API endpoint, we first need to log in. We’ll just use of the email and password combinations from our database seed file and submit it via Swagger to the login API endpoint, as shown below.

    As you can see above, the token belonging to that user is returned, indicating that the login API is working as functioning properly as intended. We can now use that token to successfully perform the GET /api/pair_programming_sessions.json operation.

    As shown, the result is returned as a properly-formatted hierarchical JSON object. Notice that the JSON structure reflects two nested 1-to-many associations, since the project has multiple reviews, and a review has multiple code samples. If we wouldn’t return the structure in this way, then the caller of our API would need to separately request the reviews for each project which would require submitting N queries to our API endpoint. With this structure, we therefore solve the N+1 query performance issue.

    Wrap-up

    As shown herein, comprehensive specs for your API help ensure that the implemented API properly and adequately addresses the intended (and unintended!) use cases.
    While the example API presented in this tutorial is fairly basic, the approach and techniques we have demonstrated can serve as the foundation for more sophisticated APIs of arbitrary complexity using the Grapegem. This tutorial has hopefully demonstrated that Grape is a useful and flexible gem that can help facilitate implementation of a JSON API in your Rails applications. Enjoy!