Run Revel Apps on Heroku

UPDATE: There have been some updates to my Revel Heroku Buildpack that make it work better and with newer versions of Revel. Check out the details.

Revel is a Play-like web framework for Go. I’m new to the Go programming language but I’ve heard good things. So I thought I’d take Revel for a spin and get it working on Heroku. Luckily there is already a Go Buildpack and a great article on how to use it.

To get Revel working on Heroku I had to make a few changes to Revel and create a modified buildpack. But it all works! Lets walk through the steps you can follow to deploy Revel apps on Heroku.

First lets get a simple Revel app working locally.
Step 1) Install Go
Step 2) Install Mercurial
Step 3) Install Git
Step 4) Create a new directory that will contain everything:

mkdir ~/go

Step 5) This new “go” directory will be your “GOPATH” so set that environment variable:

export GOPATH=~/go

Step 6) In the newly created “go” directory, get the original Revel source and my changes:

go get
go get

Step 7) Build the “revel” command:

go build -o bin/revel

Step 8) Grab my “hellorevel” sample app:

go get

Step 9) Start the local Revel server:

bin/revel run

Step 10) In your browser navigate to: http://localhost:9000

You should see a “hello, Revel” message. Lets walk through this simple app so you can get an idea of how it works.

The request you just made is mapped to code through the “conf/routes” file which contains:

# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
GET     /                                       Application.Index

This tells Revel to handle HTTP GET requests to “/” with the “Application.Index” controller.

The “Application.Index” function is defined in the “app/controllers/app.go” file and contains:

package controllers
import (
type Application struct {
func (c Application) Index() rev.Result {
    message := "hello, Revel"
    return c.Render(message)

The “Index()” function creates a “message” string of “hello, Revel” and then returns the rendered template which received the “message” as a parameter.

The “app/views/Application/Index.html” template is used to get the HTML for the “Application.Index()” controller and contains:

<!DOCTYPE html>

This uses Go templates and uses the “message” parameter.

Feel free to make changes to the template and controller to see how Revel auto-recompiles the source.

Ok, now that you have the application running locally, lets deploy it on Heroku.

Step 1) Signup for a free Heroku account
Step 2) Install the Heroku Toolbelt
Step 3) Login to Heroku from the command line (this should also setup your SSH keys if you haven’t done so already):

heroku login

Step 4) Enter the directory for the “hellorevel” app and create a new application on Heroku which will use the Revel Buildpack:

cd ~/go/src/
heroku create --buildpack

Step 5) Upload the app to Heroku using Git:

git push heroku master

This will upload the application source, pull in all of the dependencies, and then deploy the application on Heroku. That process will look something like this:

jamesw@T420s:~/go/src/$ git push heroku master
Counting objects: 25, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (19/19), done.
Writing objects: 100% (25/25), 2.46 KiB, done.
Total 25 (delta 2), reused 0 (delta 0)
-----> Heroku receiving push
-----> Fetching custom git buildpack... done
-----> Revel app detected
-----> Installing Go 1.0.3... done
       Installing Virtualenv...running virtualenv done
       Installing Mercurial... done
-----> Copying src to .go/src/pkg/_app
-----> Getting and building Revel
-----> Discovering process types
       Procfile declares types -> (none)
       Default types for Revel -> web
-----> Compiled slug size: 31.0MB
-----> Launching... done, v4 deployed to Heroku
 * [new branch]      master -> master

Step 6) Check out your Revel app on the cloud by running:

heroku open

That’s it! Deployment of Revel apps couldn’t be easier! Let me know if you have any questions or feedback on this. Thanks!

Heroku & Play Framework at JavaOne 2012

This year at JavaOne I’ll be presenting two session and participating in one BOF:

BOF4149 – Web Framework Smackdown 2012 – Monday @ 8:30pm

Much has changed since the first Web framework smackdown, at JavaOne 2005. Or has it? The 2012 edition of this popular panel discussion surveys the current landscape of Web UI frameworks for the Java platform. The 2005 edition featured JSF, Webwork, Struts, Tapestry, and Wicket. The 2012 edition features representatives of the current crop of frameworks, with a special emphasis on frameworks that leverage HTML5 and thin-server architecture. Java Champion Markus Eisele leads the lively discussion with panelists James Ward (Play), Graeme Rocher (Grails), Edward Burns (JSF) and Santiago Pericasgeertsen (Avatar).

CON3845 – Introduction to the Play Framework – Tuesday @ 8:30am

The Play Framework is a lightweight, stateless Web framework for Java and Scala applications. It’s built on Java NIO, so it’s highly scalable. This session gives you an introduction to building Web applications with the Play Framework. You will learn how to set up routes and create controllers and views, plus how to deploy Play Framework applications in the cloud.

CON3842 – Client/Server Applications with HTML5 and Java – Thursday @ 11am

The Web application landscape is rapidly shifting back to a client/server architecture. This time around, the client is JavaScript, HTML, and Cascading Style Sheets in the browser. The tools and deployment techniques for these types of applications are abundant and fragmented. This session shows you how to pull together jQuery, LESS, and Twitter Bootstrap to build the client. The server can be anything that talks HTTP, but this session uses JAX-RS. You will also learn how to deploy client/server Web applications in the cloud with a content delivery network (CDN) for the client and a PaaS for the server.

I hope to see you there!

Atlanta Presentation: Practicing Continuous Delivery

Tomorrow I’ll be presenting Practicing Continuous Delivery on the Cloud at the Atlanta No Fluff Just Stuff conference. Here is the session description:

This session will teach you best practices and patterns for doing Continuous Delivery / Continuous Deployment in Cloud environments. You will learn how to handle schema migrations, maintain dev/prod parity, manage configuration and scaling. This session will use Heroku as an example platform but the patterns could be implemented anywhere.

This has become my favorite sessions to present. So if you are going to be at Atlanta NFJS, then I hope to see you there!

Heroku at JavaZone 2012

I’m really looking forward to being back at JavaZone in Oslo this September! I’ll be speaking about Running Java, Play! and Scala Apps on the Cloud. This session will teach you how to get started deploying Java and Scala apps on Heroku. I’ll be around for the whole conference, so if anyone wants to grab a drink, deploy some apps, or write some code with me, then let me know. See you there!

Dreamforce 2012: Java Apps on Heroku &

Dreamforce 2012 is going to be a fantastic event! And not just because Red Hot Chili Peppers, Colin Powell, and Richard Branson will be there. I’ll also be there talking about Building Java Apps on Heroku and Here is the description for my session:

In this session you will learn how to build Social Enterprise applications using Salesforce, Heroku, and Java. Through live coding and demonstrations you will learn how to instantly deploy and scale Java apps on the cloud with Heroku. You will also learn how to integrate those applications with Salesforce and through REST.

Sounds pretty exciting when put next the celebrities, right? Hope to see you there!

Getting Started with Clojure on Heroku

Last week I introduced the Den of Clojure to Heroku. I really enjoyed learning more about Clojure and experiencing super simple Clojure deployment on Heroku. For those who haven’t yet deployed Clojure on Heroku, lets walk through 8 quick steps to get you started:

  1. Install the Heroku Toolbelt and Leiningen
  2. Login to Heroku from the command line:
    heroku login

    If this is your first time logging into Heroku from the command line then you will be led through some steps to associate an SSH key with your Heroku account.

  3. Create a new Leiningen build definition by creating a file named project.clj containing:
    (defproject hello-clojure-noir "0.1.0-SNAPSHOT"
      :main web
      :dependencies [[org.clojure/clojure "1.4.0"]
                     [noir "1.2.1"]])

    As you can see from the dependencies, this simple app uses the Noir web framework.

  4. Create a simple Noir app by creating a file named src/web.clj containing:
    (ns web
      (:use noir.core)
      (:require [noir.server :as server]))
    (defpage "/" [] "hello, world")
    (server/start (Integer/parseInt (or (System/getenv "PORT") "8080")))

    This very basic web app returns “hello, world” for requests to “/”. It starts the server using either the port defined by an environment variable named “PORT” or a default of 8080.

  5. Test this app locally by running:
    lein run

    Then visit http://localhost:8080 in your browser and verify that you see “hello, world”.

  6. To upload this application to Heroku you will first need to create a Git repository, add the files to it, and commit them:
    git init
    git add project.clj src
    git commit -m init
  7. Now create a new application on Heroku:
    heroku create

    This creates an HTTP and a Git endpoint for your application. The Git endpoint will be added to your Git configuration as a “remote” named “heroku”.

  8. Upload your Git repository to the Git repository for your application on Heroku:
    git push heroku master

    This will kick off the Leiningen build process on Heroku. The build will download the dependencies for the app then compile the app and put everything into a “slug” that will be deployed onto a Dyno. Once the process is complete you can open the HTTP endpoint for your app in your browser:

    heroku open

    You should now see “hello, world” coming from the Cloud!

The source for this example is on GitHub.

To learn more about Clojure on Heroku, check out the Heroku Dev Center. Let me know how it goes!

Edge Caching With Play 2, Heroku, and CloudFront

Web applications are primarily comprised of data, services, and the User Interface (UI). The UI is comprised of HTML, CSS, images, and probably JavaScript. In the traditional web architecture all of the UI assets are static files except the HTML which is dynamically generated by the server. In the modern web architecture the entire UI is static files that consume RESTful / JSON services. The static files for the UI must be downloaded to the client so the less time it takes for them to be downloaded, the better the overall performance of the application.

Bits are moved around the world through beams of light (fiber optics). Unfortunately the speed of light just isn’t fast enough when it comes to transferring data. It takes 134ms for light to travel once around the world. Think of all the light and bits that had to move from the Eastern United States (where this article is being served from) to you. Some of the time you spent waiting for the content to load was purely in the moving of bits over long distances. There is an obvious reason why physically moving bits closer to the consumer has massive performance benefits.

It would be amazing if a web application could just live right down the street from every user of the application. But doing so would cause there to be many copies of the data, services and UI for an application. The data usually needs to be consistent across all of the users of the application. Maintaining a geo-distributed and consistent data set is a really hard thing to do without massive data synchronization overhead. The services are just the gateway to the data so they need to be near the data. But the UI, all of those static assets, can easily live in many places; ideally located near the consumers.

This is exactly what a Content Delivery Network (CDN) does. Also known as “edge caching”, a CDN takes copies of static files and replicates them to servers around the world so that whenever someone downloads a static file the bits don’t have to transfer across large distances.

It has often been a big hassle to geo-distibute / edge cache the static assets in web applications. The typical setups for utilizing a CDN involve complex deployment procedures and brittle architectures. But the value of edge caching the static assets is immense for any size web application. The most effective way to improve the overall performance of just about every web application is to use a CDN.

Lets walk through how you can use the Amazon CloudFront CDN, Heroku, and Play 2 to transparently edge cache static assets. Feel free to follow along.

Create a Play 2 App

Create a new Play 2 application:

  1. Install Play 2
  2. Create a new app from the command line:
    play new play2-cloudfront
  3. Confirm the app name and select 3 for an empty project:
    jamesw@T420s:~/Desktop$ play new play2-cloudfront
           _            _ 
     _ __ | | __ _ _  _| |
    | '_ \| |/ _' | || |_|
    |  __/|_|\____|\__ (_)
    |_|            |__/ 
    play! 2.0.3,
    The new application will be created in /home/jamesw/Desktop/play2-cloudfront
    What is the application name? 
    > play2-cloudfront
    Which template do you want to use for this new application? 
      1 - Create a simple Scala application
      2 - Create a simple Java application
      3 - Create an empty project
    > 3
    OK, application play2-cloudfront is created.
    Have fun!

For this example we are going to load jQuery from a WebJar so you can remove the play2-cloudfront/public/javascripts/jquery-1.7.1.min.js file. Now update the play2-cloudfront/project/Build.scala file to include a dependency on the jQuery WebJar and the WebJars repository:

import sbt._
import Keys._
import PlayProject._
object ApplicationBuild extends Build {
    val appName         = "play2-cloudfront"
    val appVersion      = "1.0-SNAPSHOT"
    val appDependencies = Seq(
      "com.jquery" % "jquery" % "1.7.2-1"
    val main = PlayProject(appName, appVersion, appDependencies, mainLang = JAVA).settings(
      resolvers += "webjars" at ""

If you want to use IntelliJ IDEA or Eclipse then you can generate the project files. From the command line within the play2-cloudfront directory, run either:

play idea


play eclipsify

You can now start the Play server from the command line within the play2-cloudfront directory:

play ~run

Verify that the Play server is running by opening the local documentation in your browser: http://localhost:9000/@documentation

Play has a simple static asset controller that serves files from the classpath (any Jar dependency or source directory). However, the Assets Controller doesn’t provide a mechanism in its URL resolver (Play 2’s reverse routing) to change the URL of the asset. We will need this functionality later since loading assets from CloudFront requires using a different, non-relative, domain name. To solve this we will create a new RemoteAssets controller that wraps the Assets controller and optionally adds a domain prefix in front of the resolved URLs.

Create a new file named app/controllers/RemoteAssets.scala that contains:

package controllers
import play.api.mvc._
import play.api.Play
import play.api.Play.current
import org.joda.time.format.{DateTimeFormat, DateTimeFormatter}
import org.joda.time.DateTimeZone
import scala.Some
object RemoteAssets extends Controller {
  private val timeZoneCode = "GMT"
  private val df: DateTimeFormatter =
    DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss '"+timeZoneCode+"'").withLocale(java.util.Locale.ENGLISH).withZone(DateTimeZone.forID(timeZoneCode))
  type ResultWithHeaders = Result { def withHeaders(headers: (String, String)*): Result }
  def getAsset(path: String, file: String): Action[AnyContent] = Action { request =>
    val action =, file)
    val result = action.apply(request)
    val resultWithHeaders = result.asInstanceOf[ResultWithHeaders]
    resultWithHeaders.withHeaders(DATE -> df.print({new java.util.Date}.getTime))
  def getUrl(file: String) = {
    Play.configuration.getString("contenturl") match {
      case Some(contentUrl) => contentUrl + controllers.routes.RemoteAssets.getAsset(file).url
      case None => controllers.routes.RemoteAssets.getAsset(file)

This Scala class has a getAsset method that takes path and file parameters and returns the actual asset in the response. A Date header is also added to the response headers. The getUrl method takes a file parameter and returns a URL to the file. That URL will be prefixed by a contentUrl if one is provided in the application’s configuration. To setup the configuration so that a contentUrl can be optionally provided, add the following to the conf/application.conf file:


If an environment variable named CONTENT_URL is provided then the contenturl configuration parameter is set.

Now lets create and use some static content. First lets write a little CoffeeScript that will use jQuery to fade an image in. This will help to illustrate how even compiled and minimized assets can be loaded from the CDN. Create a new file named app/assets/javascripts/ containing:

$ ->

This simple script simply fades in all of the images on the page when the page has loaded.

Also update the public/stylesheets/main.css file to give the web page a new background color:

body {
    background-color: #ddddff;

Now create a new server-side template that will load the stylesheet, jQuery (from the WebJar), the script, and the public/images/favicon.png image. Create a new file named app/views/index.scala.html containing:

<!DOCTYPE html>
    <title>Play 2 with CloudFront</title>
    <link type='text/css' rel='stylesheet' href='@RemoteAssets.getUrl("stylesheets/main.css")'/>
    <script type='text/javascript' src='@RemoteAssets.getUrl("jquery.min.js")'></script>
    <script type='text/javascript' src='@RemoteAssets.getUrl("javascripts/index.min.js")'></script>
    <img src='@RemoteAssets.getUrl("images/favicon.png")' style="display: none;"/>

Notice how the getUrl method in the RemoteAssets controller is used to get a URL for each asset. Now we need a simple controller that will render the index template. Create a new file named app/controllers/ containing:

package controllers;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.index;
public class Application extends Controller {
  public static Result index() {
    return ok(index.render());

This controller has a single method named index that just returns the rendered index template with a 200 HTTP status.

The last thing to do is to create a mapping between HTTP request verbs & paths and the controller that serves the request. Edit the conf/routes file and add the following:

# Home page
GET     /                           controllers.Application.index()
# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file               controllers.RemoteAssets.getAsset(path="/public", file)

Now GET requests to / will be handled by the controllers.Application.index method and GET requests to /assets/ will be handled by the controllers.RemoteAssets.getAsset method.

This simple little application is now ready for local testing. Open it in your browser: http://localhost:9000

You should see the Play logo fade in on top of a purple-ish background. This page required a total of five HTTP requests:

Local HTTP Requests

Lets take this application and deploy it on the cloud with Heroku and then we will setup CloudFront to serve the static assets.

Deploy on Heroku

Heroku is a Cloud Application Platform that can run many different types of apps. To deploy this application on Heroku:

  1. Signup for a Heroku Account
    Note: These instructions will not use Heroku beyond the free tier.
  2. Install Git (Or use Git from your IDE)
  3. Install the Heroku Toolbelt
  4. Login to Heroku from the command line:
    heroku login

    If this is your first time using the Heroku Toolbelt then you will be led through the steps to associate an SSH key with your Heroku account. This SSH key will be used to authenticate your uploads via Git.

  5. From the command line in your play2-cloudfront directory, create a new Git repository, add your files to it, and commit them:
    git init
    git add app conf project public
    git commit -m init
  6. From the command line in your play2-cloudfront directory, provision a new application on Heroku:
    heroku create

    This will create a new application with corresponding HTTP and Git endpoints, like:

    Creating peaceful-retreat-3158... done, stack is cedar |
    Git remote heroku added
  7. To deploy your application on Heroku simply upload your Git repository to Heroku:
    git push heroku master

    This will push the master branch of your Git repository to the Git remote named heroku which in my case points to the URL. When Heroku receives the files it will run the project build (SBT for Play 2 projects), then deploy and run the application. When the application is running you can access it in your browser:

    heroku open

This time all five requests go to Heroku:

Local HTTP Requests

The requests take quite a bit longer than locally, in-part because the bits have a much larger distance to travel. All of the requests except the index page (because it’s dynamic) can be served from a CDN. Now lets setup CloudFront to serve the static assets.

Serve Static Assets with CloudFront

CloudFront has a very simple way to load static assets into it’s CDN. When a request comes into CloudFront, if the asset is not on the CDN or has expired, then CloudFront can get the asset from an “origin server”. The application you just deployed on Heroku will now be the origin server for the static assets. To setup a new CloudFront “Distribution”:

  1. Signup for a AWS Account
    Note: CloudFront does not have a free tier. So following these instructions will cost you a tiny bit.
  2. Open the CloudFront Management Console
  3. Select Create Distribution
  4. Leave Download selected as the delivery method and select Continue
  5. In the Origin Domain Name field enter the domain name for your application on Heroku. In my case it is:
  6. Keep the other default values as-is and select Continue

    CloudFront Setup

  7. Do the same for the next two steps (keep the defaults)
  8. Select Create Distribution

It will now take about ten minutes for AWS to create the CloudFront distribution. You can monitor the status in the AWS Console. While you wait, take note of the domain name provided for your distribution. Mine is:

You can test the status of distribution by making a request for the favicon.png file. In my case the full URL is:

The first time that request goes through, CloudFront will make a request back to the app on Heroku and then load the asset into the CDN. If you examine the HTTP response headers on that request you will see:

X-Cache: Miss from cloudfront

That indicates that the resource was not on the CDN. A subsequent request should contain the following response header:

X-Cache: Hit from cloudfront

That indicates that the resource was served from the CDN and there was no need to go back to the origin server.

Now that the static assets are loadable via CloudFront lets tell the app on Heroku and the RemoteAssets controller to point to them. Just set the CONTENT_URL environment variable on your application by running the following from the command line (make sure you replace the URL value with the one for the distribution you just created):

heroku config:add CONTENT_URL=""

Now test out your application on Heroku in your browser:

heroku open

You should now see all four static asset requests going to CloudFront:

Heroku and CloudFront - Miss

But as you can see they assets didn’t load very quickly because the first request is a Miss from cloudfront. Reload the page (clear your cache to avoid 304s) and you should see much faster responses:

Heroku and CloudFront - Hit

And now your static assets are being edge cached!

Learn More

Using a CDN is step one of significantly speeding up your web applications but there is certainly more that you can do. By default Play sets the expiration time of static assets to 1 hour (via the Cache-Control response header):

Cache-Control: max-age=3600

You can change that value by modifying the application.conf file (more details). Often times you will also want to use far future expires and use naming conventions to instruct the client to fetch a new version of a static asset.

Grab the source for this example.

Check out the live demo.

Let me know if you have any questions.

UPDATE: Check out the Play 2 CloudFront Module!