Enabling API caching

Application Programming Interfaces (APIs) allow you to retrieve data from a variety of web services. Fastly makes it possible for you to cache your API so you can accelerate the performance of your service-oriented architecture. It optimizes your API's performance by efficiently handling traffic bursts and reducing latency.

This guide consists of three parts:

An example

Let's look at an example to learn how API caching works. Imagine we're an online magazine with articles on which users can make comments. Each article can have many comments, and each comment is authored by exactly one user.

Relational schema for the database of the website.

We'll design a RESTful API specification and use it to manipulate and retrieve comments:

The create, read, update, and delete (CRUD) methods ensure the API can perform its basic operations, but they don't expose the relational aspect of the data. To do so, you would add a couple of relational endpoints:

Endpoints like these allow programmers to get the information they need to do things like render the HTML page for an article, or display comments on a user's profile page. While there are many other possible endpoints we could construct, this set should suffice for the purposes of this guide. Let's assume that the API has been programmed to use an Object-Relational Mapper (ORM), such as ActiveRecord, when interacting with the database.

Determining which API endpoints to cache

Start by identifying the URLs you want to cache. We recommend splitting the specification endpoints into two groups.

The first group, called "accessors," retrieves or accesses the comment data. These are the endpoints you want to cache using Fastly. Using the example, four endpoints match this description:

The second group, called "mutators," changes or mutates the comment data. These endpoints are always dynamic, and are therefore uncacheable. Using the example, three endpoints match this description:

You should see a pattern emerging. Because the example API is RESTful, we can use a simple rule to identify the accessor and mutator endpoints: GET endpoints can be cached, but PUT, POST, and DELETE endpoints cannot.

Once you've gathered this information, you're ready to program the API to configure PURGE requests.

Configuring PURGE requests

Don't be tempted to point at the PUT, POST, and DELETE endpoints as the place where data is modified. In most modern APIs, these endpoints represent an interface to the actual model code responsible for handling the database modifications.

In the example, we assumed that we'd be using an ORM to perform the actual database work. Most ORMs allow programmers to set special "callbacks" on models that will fire when certain actions have been performed (e.g., before or after validation, or after creating a new record).

For purging, we are interested in whether a model has saved information to the database — whether it's a new record, an update to an existing record, or the deleting of a record. At this point, we'd add a callback that tells the API to send a PURGE request to Fastly for each of the cacheable endpoints.

For an ActiveRecord comments model, you could do something like this:

require 'fastly'

class Comment < ActiveRecord::Base
  fastly = Fastly.new(api_key: 'MY_API_KEY')

  after_save do
    fastly.purge "/comment"
    fastly.purge "/comment/#{self.id}"
    fastly.purge "/article/#{self.article_id}/comments"
    fastly.purge "/user/#{self.user_id}/comments"

Keep two things in mind when creating the callback:

With the model code in place, the API is now ready to be cached.

Setting up Fastly

The final step is setting up Fastly. You'll need to perform the following steps:

In addition, you can optionally create rules that tell Fastly how to work with the specific elements that are exclusive to your API.

Creating a new service

Follow these instructions to add a new service to your Fastly account:

  1. Log in to the Fastly application.
  2. Click the configure tab (wrench icon).

    Select the configure tab.

  3. Click the green New Service button. The New Service window appears.

    The New Service window.

  4. Fill out the New Service fields as follows:

    • In the Name field, type a name for this service (e.g., My API Service).
    • In the Origin Server Address field, type the IP address of your API server.
    • In the Domain Name field, type the domain name associated with your API (e.g., api.example.com).
  5. Click Create.

Your service now appears in the Service menu.

Adding the domain

Follow these instructions to add the API's domain name to your Fastly service:

  1. From the Service menu, select the service you just created and then click the blue Configure button. The main controls for your selected service appear.
  2. Click Domains from the section list on the left. The Domains page appears.

    The Domains page.

  3. Click New. The New Domain window appears.

    The New Domain window.

  4. Fill out the New Domain window as follows:

    • In the Domain Name field, type the domain name for the API.
    • In the Comment field, optionally type a comment.
  5. Click Create. Your API's domain name appears in the list of domains.

Adding the origin server

Follow these instructions to add the origin server that runs the API software to your Fastly service:

  1. Click Hosts from the section list on the left. The Hosts page appears.

    The Hosts page.

  2. In the Backends area, click the New button. The New Backend window appears.

    The New Backend window.

  3. Fill out the New Backend fields as follows:

    • In the Address field, type the IP address or hostname and port number of the origin server for your API.
    • In the Name field, type a name for this origin server (e.g., My API Server).
    • From the Health Check menu, optionally select a health check for this origin server. For more information, see our health checks tutorial.
    • From the Auto Load Balance menu, select an option to enable or disable load balancing for this origin server. For more information, see our guide on load balancing.
    • If you enabled load balancing, type a weight in the Weight field.
    • If you'd like to use the shielding feature, select a POP from the Shielding menu.
  4. Click Create. The origin server appears in the list of origin servers.

Back to Top