SlideShare une entreprise Scribd logo
1  sur  40
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?

Contenu connexe

Tendances

Tendances (20)

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

Similaire à Building a scalable API with Grails

AngularJSTO presentation
AngularJSTO presentationAngularJSTO presentation
AngularJSTO presentation
Alan Hietala
 

Similaire à Building a scalable API with Grails (20)

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

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

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