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

What's hot (20)

PDF
API for Beginners
Gustavo De Vita
 
PPTX
Secure rest api on microservices vws2016
Quý Nguyễn Minh
 
PDF
Declaring Server App Components in Pure Java
Atlassian
 
PDF
Why your next serverless project should use AWS AppSync
Yan Cui
 
PPTX
Building a REST Service in minutes with Spring Boot
Omri Spector
 
PDF
Meet the Forge Runtime
Atlassian
 
PDF
Building a Cerberus App Without Losing Our Heads: The Passage to a Cross-Plat...
Atlassian
 
PPTX
Scaling with swagger
Tony Tam
 
PDF
Coding 100-session-slides
Cisco DevNet
 
PPTX
Amazon API Gateway
Mark Bate
 
PDF
"Design First" APIs with Swagger
scolestock
 
PDF
In The Trenches With Tomster, Upgrading Ember.js & Ember Data
Stacy London
 
PDF
Amazon API Gateway を活用したゲームサーバー構築
崇之 清水
 
KEY
Birdpie
anupnarkhede
 
PDF
Observability and Troubleshooting in Forge
Atlassian
 
PDF
Lightning Chess at the Sri Sanka Salesforce Developer Group
Samuel De Rycke
 
PDF
Integrating consumers IoT devices into Business Workflow
Yakov Fain
 
PPTX
Raml part 1
venkata20k
 
PPTX
Chef Actions: Delightful near real-time activity tracking!
James Casey
 
PDF
Designing and Running a GraphQL API
Atlassian
 
API for Beginners
Gustavo De Vita
 
Secure rest api on microservices vws2016
Quý Nguyễn Minh
 
Declaring Server App Components in Pure Java
Atlassian
 
Why your next serverless project should use AWS AppSync
Yan Cui
 
Building a REST Service in minutes with Spring Boot
Omri Spector
 
Meet the Forge Runtime
Atlassian
 
Building a Cerberus App Without Losing Our Heads: The Passage to a Cross-Plat...
Atlassian
 
Scaling with swagger
Tony Tam
 
Coding 100-session-slides
Cisco DevNet
 
Amazon API Gateway
Mark Bate
 
"Design First" APIs with Swagger
scolestock
 
In The Trenches With Tomster, Upgrading Ember.js & Ember Data
Stacy London
 
Amazon API Gateway を活用したゲームサーバー構築
崇之 清水
 
Birdpie
anupnarkhede
 
Observability and Troubleshooting in Forge
Atlassian
 
Lightning Chess at the Sri Sanka Salesforce Developer Group
Samuel De Rycke
 
Integrating consumers IoT devices into Business Workflow
Yakov Fain
 
Raml part 1
venkata20k
 
Chef Actions: Delightful near real-time activity tracking!
James Casey
 
Designing and Running a GraphQL API
Atlassian
 

Similar to Building a scalable API with Grails (20)

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

Recently uploaded (20)

PDF
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PPTX
Simplifica la seguridad en la nube y la detección de amenazas con FortiCNAPP
Cristian Garcia G.
 
PPTX
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
PDF
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
PDF
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
 
PDF
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
PDF
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
PPSX
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PDF
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
PPTX
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
PPTX
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
PDF
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
PDF
The Growing Value and Application of FME & GenAI
Safe Software
 
PDF
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
PDF
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
PDF
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Simplifica la seguridad en la nube y la detección de amenazas con FortiCNAPP
Cristian Garcia G.
 
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
Unlocking FME Flow’s Potential: Architecture Design for Modern Enterprises
Safe Software
 
UiPath Agentic AI ile Akıllı Otomasyonun Yeni Çağı
UiPathCommunity
 
Hyderabad MuleSoft In-Person Meetup (June 21, 2025) Slides
Ravi Tamada
 
My Journey from CAD to BIM: A True Underdog Story
Safe Software
 
Usergroup - OutSystems Architecture.ppsx
Kurt Vandevelde
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Automating the Geo-Referencing of Historic Aerial Photography in Flanders
Safe Software
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
MARTSIA: A Tool for Confidential Data Exchange via Public Blockchain - Poster...
Michele Kryston
 
Plugging AI into everything: Model Context Protocol Simplified.pdf
Abati Adewale
 
The Growing Value and Application of FME & GenAI
Safe Software
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
Darley - FIRST Copenhagen Lightning Talk (2025-06-26) Epochalypse 2038 - Time...
treyka
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Redefining Work in the Age of AI - What to expect? How to prepare? Why it mat...
Malinda Kapuruge
 
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
Ad

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