SlideShare a Scribd company logo
Building a scalable API with
                      Grails



         Greach – 2013-01-26
             Tanausú Cerdeña
      @chozero | @geosophers
What you can expect from this talk
•   A story of an API creation on Grails.
•   Decisions made and the reasons behind.
•   Pitfalls.
•   We’re learning as we go.
About me
• Tanausú Cerdeña (@chozero)

• Sysadmin background.

• Grails user for two years.

• Co-founder and CTO at Geosophic.
Let’s get some context first


Online services for mobile games:
• Gaming features: Leaderboards, player
  matching…
• Data tracking: levels played, session duration…
• Monetization: Performance ad serving.
Let’s get some context first


Online services for mobile games:
• Gaming features: Leaderboards, player
  matching…
• Data tracking: levels played, session duration…
• Monetization: Performance ad serving.
Why Grails?
1. Productivity. Geosophic started as
   an MVP.
2. Java experience on the team.
3. It’s fun to use! (+15% developer
   happiness).
Our development environment
• Grails 2.1.1 / Groovy 1.8.8
• STS / vim. Trying to move to Intellij (thanks
  doomsday!!)
• Deployed to AWS (Elastic Beanstalk).
• Team of 3 developers:
   • 1 backend, 1 frontend, 1 mobile
   • Everyone touches everything.
Overview of architecture
Android              iOS
 SDK                 SDK


          HTTP API                       Dashboard (Grails)


   API Controllers                    Dashboard Controllers

                           Services

   Domain Objects



           MySQL                         Redis
API Controllers
• Lightweight:
   • Validate parameters
   • Call required services
   • Compose responses
API Controllers
API Design
Top-down design:
• URLs.
• (HTTP) Methods (Fully REST
  compliant?)
• Response format.
• Versioning.
• Authentication.
API Design: URL schema
http://{baseURL}/{version}/{feature}/{item}/{action?}


http://api.geosophic.com/v1/leaderboards/leaderboard/nearest

http://api.geosophic.com/v1/leaderboards/score

http://api.geosophic.com/v1/track/event
API Design: Versioning options
In the URL path?
   http://my.api.com/v1/endpoint
As a URL parameter?
   http://my.api.com/endpoint??v=1
Custom HTTP Header?
  Accept-Version: 1
Versioned media types?
  Accept: application/vnd.myapp-v1+json
API Design: Versioning options
In the URL path?
   http://my.api.com/v1/endpoint
As a URL parameter?
   http://my.api.com/endpoint??v=1
Custom HTTP Header?
  Accept-Version: 1
Versioned media types?
  Accept: application/vnd.myapp-v1+json
API Design: Versioning issues
• Scarcity of resources to handle different
  versions.
• Backwards compatibility?
• Our first client deployed, a week later, we
  decided a change on the API.
• Mobile clients (apps) don’t update that often.
HTTP methods
Our API model doesn’t match perfectly with a CRUD
model so no fully REST API.

• GET: Retrieving info.
  • Get a leaderboard
• POST: Submitting info.
  • Send a score.
  • Submit an event.
API Design: URL mappings
API Design: Response format
Only JSON. No XML
{
    meta: {
       apiVersion: “1.0.1”,
       code: 400,
       errorType: “User id required”,
       msgs: []
    },
    response: {
       // Content depends on endpoint
    },
    notifications: { // Future use }
}
API Design: Response format
Rendering response
render as JSON:
• We have a mix of domain classes and other
   objects to render.
• Write custom JSON Marshaller for some
   classes.
• Register them at BootStrap.groovy.
Rendering JSON response
Rendering JSON response
DRY in our API Controllers
We have some common code for all our API
endpoints:
• Authentication.
• API usage tracking.
• Common parameters validation.
@Mixin: ApiController
@Mixin: ApiController
@Mixin: ApiController
Also includes some helper methods:
@Mixin: Issues
• Class reloading when in development
API Design: Authentication
• (consumer key, consumer secret) per
  client.
• Consumer key used to identify the
  client (sent as a URL parameter).
• Consumer secret to sign the request.
• This is (sort of) 2-legged Oauth.
API Design: Authentication
• Some plugins implementing clients,
  but no suitable (for us) server
  implementation (maybe we didn’t look
  deep enough?).
• Better to use SpringSecurity and
  customize?
• We are feeling more confident and
  want to contribute this.
API Design: Handling errors
• 400 handled by each Controller
• 500 handled by ErrorController
  (mapped in UrlMappings.groovy)
API Design: Handling errors
Measuring API usage
• In ApiController beforeInterceptor
• Fire and forget (runAsync in the
  service)
• Now to MySQL, moving to Redis
Measuring API usage
Testing
• Test Api Controllers as any other
  controller
• All bussiness logic in Services
• Remember to include the Mixin:
Testing
Performance considerations
• No GSPs but JSON so quite fast.
• Asynchronous tracking helps.
• Difficult to cache (except for
  leaderboards). We cache in the
  service.
Some performance figures
• 1 EC2 small instance(1.7GB RAM)
• API + Services + Dashboard
• 90K users, 7K daily active.
• Throughput: ~ 75 rpm (peaks of 200)
• Server response time: ~ 160 ms
  average
• Performance tests: up to 450 rpm
Bottlenecks
• Database: MySQL
• Redis for most read data:
  • Gaming features (leaderboards)
• Evaluating metrics storage:
  • Redis
  • Cube (from Square)
Next steps
• Improve the API usage tracking.
• Spock.
• See what we can contribute (Auth? API
  usage?)
• Looking for a nice log viewer solution
¡Thanks!



¿Questions and/or suggestions?

More Related Content

PDF
Building Awesome APIs in Grails
PDF
Creating RESTful API’s with Grails and Spring Security
PDF
Exposing Salesforce REST Services Using Swagger
PPT
API 101 - Understanding APIs
PDF
Getting Started With Angular
PPTX
An introduction to the API for OnTime for IBM
PDF
API Prefetching - HTML5DevConf - Oct. 21, 2014
PPTX
A Tasty deep-dive into Open API Specification Links
Building Awesome APIs in Grails
Creating RESTful API’s with Grails and Spring Security
Exposing Salesforce REST Services Using Swagger
API 101 - Understanding APIs
Getting Started With Angular
An introduction to the API for OnTime for IBM
API Prefetching - HTML5DevConf - Oct. 21, 2014
A Tasty deep-dive into Open API Specification Links

What's hot (20)

PDF
API for Beginners
PPTX
Secure rest api on microservices vws2016
PDF
Declaring Server App Components in Pure Java
PDF
Why your next serverless project should use AWS AppSync
PPTX
Building a REST Service in minutes with Spring Boot
PDF
Meet the Forge Runtime
PDF
Building a Cerberus App Without Losing Our Heads: The Passage to a Cross-Plat...
PPTX
Scaling with swagger
PDF
Coding 100-session-slides
PPTX
Amazon API Gateway
PDF
"Design First" APIs with Swagger
PDF
In The Trenches With Tomster, Upgrading Ember.js & Ember Data
PDF
Amazon API Gateway を活用したゲームサーバー構築
KEY
Birdpie
PDF
Observability and Troubleshooting in Forge
PDF
Lightning Chess at the Sri Sanka Salesforce Developer Group
PDF
Integrating consumers IoT devices into Business Workflow
PPTX
Raml part 1
PPTX
Chef Actions: Delightful near real-time activity tracking!
PDF
Designing and Running a GraphQL API
API for Beginners
Secure rest api on microservices vws2016
Declaring Server App Components in Pure Java
Why your next serverless project should use AWS AppSync
Building a REST Service in minutes with Spring Boot
Meet the Forge Runtime
Building a Cerberus App Without Losing Our Heads: The Passage to a Cross-Plat...
Scaling with swagger
Coding 100-session-slides
Amazon API Gateway
"Design First" APIs with Swagger
In The Trenches With Tomster, Upgrading Ember.js & Ember Data
Amazon API Gateway を活用したゲームサーバー構築
Birdpie
Observability and Troubleshooting in Forge
Lightning Chess at the Sri Sanka Salesforce Developer Group
Integrating consumers IoT devices into Business Workflow
Raml part 1
Chef Actions: Delightful near real-time activity tracking!
Designing and Running a GraphQL API
Ad

Similar to Building a scalable API with Grails (20)

PPTX
Cloudsolutionday 2016: Getting Started with Severless Architecture
PDF
Services Over Servers - Innovate VA 2016
PDF
AngularJSTO presentation
PDF
PPTX
AWS and Serverless with Alexa
PPTX
Angular2.0@Shanghai0319
PDF
GlueCon 2015 - How REST APIs can glue all types of devices together
PDF
Design & Deploy a data-driven Web API in 2 hours
PPTX
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
PPTX
API City 2019 Presentation - Delivering Developer Tools at Scale: Microsoft A...
PPTX
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
PDF
A look ahead at RAP (ESE 2010)
PDF
API workshop by AWS and 3scale
PPTX
Lessons learned on the Azure API Stewardship Journey.pptx
PDF
API Design Workflows
PPTX
Tokyo Azure Meetup #7 - Introduction to Serverless Architectures with Azure F...
PDF
Kubernetes Architecture - beyond a black box - Part 1
PDF
SGCE 2015 REST APIs
PDF
APIs distribuidos con alta escalabilidad
PPTX
API Services: Building State-of-the-Art APIs
Cloudsolutionday 2016: Getting Started with Severless Architecture
Services Over Servers - Innovate VA 2016
AngularJSTO presentation
AWS and Serverless with Alexa
Angular2.0@Shanghai0319
GlueCon 2015 - How REST APIs can glue all types of devices together
Design & Deploy a data-driven Web API in 2 hours
MongoDB World 2018: Ch-Ch-Ch-Ch-Changes: Taking Your Stitch Application to th...
API City 2019 Presentation - Delivering Developer Tools at Scale: Microsoft A...
apidays LIVE Australia 2020 - Have your cake and eat it too: GraphQL? REST? W...
A look ahead at RAP (ESE 2010)
API workshop by AWS and 3scale
Lessons learned on the Azure API Stewardship Journey.pptx
API Design Workflows
Tokyo Azure Meetup #7 - Introduction to Serverless Architectures with Azure F...
Kubernetes Architecture - beyond a black box - Part 1
SGCE 2015 REST APIs
APIs distribuidos con alta escalabilidad
API Services: Building State-of-the-Art APIs
Ad

Recently uploaded (20)

PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
KodekX | Application Modernization Development
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Approach and Philosophy of On baking technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Modernizing your data center with Dell and AMD
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
Advanced methodologies resolving dimensionality complications for autism neur...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
KodekX | Application Modernization Development
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
NewMind AI Weekly Chronicles - August'25 Week I
NewMind AI Monthly Chronicles - July 2025
Chapter 3 Spatial Domain Image Processing.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Approach and Philosophy of On baking technology
“AI and Expert System Decision Support & Business Intelligence Systems”
Modernizing your data center with Dell and AMD
The AUB Centre for AI in Media Proposal.docx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Diabetes mellitus diagnosis method based random forest with bat algorithm
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Per capita expenditure prediction using model stacking based on satellite ima...

Building a scalable API with Grails

  • 1. Building a scalable API with Grails Greach – 2013-01-26 Tanausú Cerdeña @chozero | @geosophers
  • 2. What you can expect from this talk • A story of an API creation on Grails. • Decisions made and the reasons behind. • Pitfalls. • We’re learning as we go.
  • 3. About me • Tanausú Cerdeña (@chozero) • Sysadmin background. • Grails user for two years. • Co-founder and CTO at Geosophic.
  • 4. Let’s get some context first Online services for mobile games: • Gaming features: Leaderboards, player matching… • Data tracking: levels played, session duration… • Monetization: Performance ad serving.
  • 5. Let’s get some context first Online services for mobile games: • Gaming features: Leaderboards, player matching… • Data tracking: levels played, session duration… • Monetization: Performance ad serving.
  • 6. Why Grails? 1. Productivity. Geosophic started as an MVP. 2. Java experience on the team. 3. It’s fun to use! (+15% developer happiness).
  • 7. Our development environment • Grails 2.1.1 / Groovy 1.8.8 • STS / vim. Trying to move to Intellij (thanks doomsday!!) • Deployed to AWS (Elastic Beanstalk). • Team of 3 developers: • 1 backend, 1 frontend, 1 mobile • Everyone touches everything.
  • 8. Overview of architecture Android iOS SDK SDK HTTP API Dashboard (Grails) API Controllers Dashboard Controllers Services Domain Objects MySQL Redis
  • 9. API Controllers • Lightweight: • Validate parameters • Call required services • Compose responses
  • 11. API Design Top-down design: • URLs. • (HTTP) Methods (Fully REST compliant?) • Response format. • Versioning. • Authentication.
  • 12. API Design: URL schema http://{baseURL}/{version}/{feature}/{item}/{action?} http://api.geosophic.com/v1/leaderboards/leaderboard/nearest http://api.geosophic.com/v1/leaderboards/score http://api.geosophic.com/v1/track/event
  • 13. API Design: Versioning options In the URL path? http://my.api.com/v1/endpoint As a URL parameter? http://my.api.com/endpoint??v=1 Custom HTTP Header? Accept-Version: 1 Versioned media types? Accept: application/vnd.myapp-v1+json
  • 14. API Design: Versioning options In the URL path? http://my.api.com/v1/endpoint As a URL parameter? http://my.api.com/endpoint??v=1 Custom HTTP Header? Accept-Version: 1 Versioned media types? Accept: application/vnd.myapp-v1+json
  • 15. API Design: Versioning issues • Scarcity of resources to handle different versions. • Backwards compatibility? • Our first client deployed, a week later, we decided a change on the API. • Mobile clients (apps) don’t update that often.
  • 16. HTTP methods Our API model doesn’t match perfectly with a CRUD model so no fully REST API. • GET: Retrieving info. • Get a leaderboard • POST: Submitting info. • Send a score. • Submit an event.
  • 17. API Design: URL mappings
  • 18. API Design: Response format Only JSON. No XML { meta: { apiVersion: “1.0.1”, code: 400, errorType: “User id required”, msgs: [] }, response: { // Content depends on endpoint }, notifications: { // Future use } }
  • 20. Rendering response render as JSON: • We have a mix of domain classes and other objects to render. • Write custom JSON Marshaller for some classes. • Register them at BootStrap.groovy.
  • 23. DRY in our API Controllers We have some common code for all our API endpoints: • Authentication. • API usage tracking. • Common parameters validation.
  • 26. @Mixin: ApiController Also includes some helper methods:
  • 27. @Mixin: Issues • Class reloading when in development
  • 28. API Design: Authentication • (consumer key, consumer secret) per client. • Consumer key used to identify the client (sent as a URL parameter). • Consumer secret to sign the request. • This is (sort of) 2-legged Oauth.
  • 29. API Design: Authentication • Some plugins implementing clients, but no suitable (for us) server implementation (maybe we didn’t look deep enough?). • Better to use SpringSecurity and customize? • We are feeling more confident and want to contribute this.
  • 30. API Design: Handling errors • 400 handled by each Controller • 500 handled by ErrorController (mapped in UrlMappings.groovy)
  • 32. Measuring API usage • In ApiController beforeInterceptor • Fire and forget (runAsync in the service) • Now to MySQL, moving to Redis
  • 34. Testing • Test Api Controllers as any other controller • All bussiness logic in Services • Remember to include the Mixin:
  • 36. Performance considerations • No GSPs but JSON so quite fast. • Asynchronous tracking helps. • Difficult to cache (except for leaderboards). We cache in the service.
  • 37. Some performance figures • 1 EC2 small instance(1.7GB RAM) • API + Services + Dashboard • 90K users, 7K daily active. • Throughput: ~ 75 rpm (peaks of 200) • Server response time: ~ 160 ms average • Performance tests: up to 450 rpm
  • 38. Bottlenecks • Database: MySQL • Redis for most read data: • Gaming features (leaderboards) • Evaluating metrics storage: • Redis • Cube (from Square)
  • 39. Next steps • Improve the API usage tracking. • Spock. • See what we can contribute (Auth? API usage?) • Looking for a nice log viewer solution