Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The Power of Serverless GraphQL with AppSync

The Power of Serverless GraphQL with AppSync

ServerlessDays Virtual, October 2020. https://virtual.serverlessdays.io/speakers/202010/slobodan/

Slobodan Stojanović

October 28, 2020
Tweet

More Decks by Slobodan Stojanović

Other Decks in Programming

Transcript

  1. he!o!
    ServerlessDays Virtual

    View Slide

  2. every story n"ds a hero

    View Slide

  3. View Slide

  4. Our hero

    View Slide

  5. Works in a sma! team
    on a mid-sized application

    View Slide

  6. Most of the time
    enjoys the job

    View Slide

  7. Just sent a test push notification
    to thousands of customers

    View Slide

  8. We need to build this new complex app.

    View Slide

  9. Ok, no problem

    View Slide

  10. But we have a short deadline.

    View Slide

  11. Ok, how short?

    View Slide

  12. It needs to be ready for yesterday. And it needs to be scalable and real-time!

    View Slide


  13. View Slide

  14. How should I build this?

    View Slide

  15. Don't worry, we have a famous consultant that will help you architecture the app.

    View Slide

  16. Great!

    View Slide

  17. multi-cloud
    guru

    View Slide

  18. Just use Kubernetes!
    multi-cloud
    guru

    View Slide

  19. But I don't know Kubernetes.

    View Slide

  20. I don't have time to learn Kubernetes now.

    View Slide

  21. What should I do?

    View Slide

  22. Am I the only one who don't know Kubernetes?

    View Slide

  23. Maybe I am not good enough for this!

    View Slide

  24. View Slide

  25. Serverless GraphQL
    You should try

    View Slide

  26. Serverless GraphQL?

    View Slide

  27. Serverless GraphQL
    with AppSync
    The Power of

    View Slide

  28. @slobodan_
    Before we continue…

    View Slide

  29. Slobodan Stojanović
    CTO @ Cloud Horizon & CTO @ Vacation Tracker
    co-author of Serverless Applications with Node.js book
    AWS Serverless Hero
    @slobodan_

    View Slide

  30. Serverless GraphQL
    with AppSync
    The Power of

    View Slide

  31. Serverless GraphQL
    ?

    View Slide

  32. What's GraphQL?

    View Slide

  33. @slobodan_
    "Our biggest mistake was betting too much on HTML5"
    Mark Zuckerberg, 2012

    View Slide

  34. @slobodan_

    View Slide

  35. @slobodan_
    HTML
    HTML

    View Slide

  36. @slobodan_
    "Our biggest mistake was betting too much on HTML5"
    Mark Zuckerberg, 2012

    View Slide

  37. @slobodan_
    REST? FQL?
    REST? FQL?

    View Slide

  38. @slobodan_
    "We were frustrated with the differences between the data we
    wanted to use in our apps and the server queries they required."
    L" Byron, 2015
    GraphQL: A data query language article

    View Slide

  39. @slobodan_
    Data app needs
    Data app needs

    View Slide

  40. @slobodan_

    View Slide

  41. Nice. But, why should I care about GraphQL?

    View Slide

  42. I don't have the same problems as Facebook.

    View Slide

  43. Ok, but let's s" if you have one of the fo!owing problems

    View Slide

  44. Distinct frontend clients
    for multiple platforms (i.e., web and mobile)
    has different data requirements.

    View Slide

  45. A backend serves data
    to clients
    from different sources.

    View Slide

  46. A complex state and caching managements
    for both
    frontend and backend.

    View Slide

  47. Slow pages
    especia!y on mobile, caused by
    multiple dependant HTTP requests.

    View Slide

  48. These are just some "symptoms"
    that GraphQL can cure.

    View Slide

  49. • Defines a data shape
    • Hierarchical
    • Strongly typed
    • Protocol, not storage
    • Introspective
    • Version fr"

    View Slide

  50. View Slide

  51. View Slide

  52. Types
    type Author {
    id: Int
    name: String
    posts: [Post]
    }
    type Post {
    id: Int
    title: String
    text: String
    author: Author
    }

    View Slide

  53. Schema
    type Query {
    getAuthor(id: Int): Author
    getPostsByTitle(titleContains: String): [Post]
    }
    schema {
    query: Query
    }

    View Slide

  54. Resolvers
    getAuthor(_, args){
    return sql.raw('SELECT * FROM authors WHERE id = %s', args.id);
    }
    posts(author){
    return request(`https://api.blog.io/by_author/${author.id}`);
    }

    View Slide

  55. Queries
    {
    getAuthor(id: 5){
    name
    posts {
    title
    author {
    # this will be the same as the name above
    name
    }
    }
    }
    }

    View Slide

  56. 1. Parse
    2. Validate
    3. Execute

    View Slide

  57. Result
    {
    "name": "Slobodan",
    "posts": [{
    "title": "Hello World",
    "author": {
    "name": "Slobodan"
    }
    }, {
    "title": "GraphQL",
    "author": {
    "name": "Slobodan"
    }
    }]
    }

    View Slide

  58. GraphQL supports:
    • Queries
    • Mutations
    • Subscriptions

    View Slide

  59. Interesting!

    View Slide

  60. Serverless GraphQL

    View Slide

  61. Serverless GraphQL
    Why?

    View Slide

  62. GraphQL using
    Kubernetes
    We!, you can deploy

    View Slide

  63. BUT
    there's an
    easier way

    View Slide

  64. View Slide

  65. You sti! n"d to scale these

    View Slide

  66. Unless you make it serverless

    View Slide

  67. How can I make my GraphQL app serverless?

    View Slide

  68. You can make it manua!y

    View Slide

  69. Or you can use AWS AppSync!

    View Slide

  70. What's AWS AppSync?

    View Slide

  71. AppSync is a managed service that uses GraphQL to make it easy
    for applications to get exactly the data they n"d.

    View Slide

  72. AppSync to develop
    your app faster
    You can use

    View Slide

  73. I can? How?

    View Slide

  74. • Define GraphQL schema
    • Automatically provision a DynamoDB data
    source and connect resolvers
    • Write GraphQL queries and mutations
    • Use the API in the frontend app

    View Slide

  75. It's easy to
    start with
    Let's give it a try

    View Slide

  76. You can start with the guided schema wizard
    on AWS Web Console

    View Slide

  77. But you should use AWS Amplify, CloudFormation or CDK
    for more serious apps

    View Slide

  78. View Slide

  79. > amplify init
    > amplify add api
    > amplify push

    View Slide

  80. Wow, that was fast!

    View Slide

  81. I should show it to the consultant.

    View Slide

  82. That will never work!
    Amplify is not
    good enough.
    multi-cloud
    guru

    View Slide

  83. You can always start with Amplify and then move to
    CloudFormation or CDK

    View Slide

  84. AppSync with CDK
    import * as cdk from '@aws-cdk/core';
    import * as appsync from '@aws-cdk/aws-appsync';
    export class AppsyncCdkAppStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);
    // Creates the AppSync API
    const api = new appsync.GraphqlApi(this, 'Api', {
    name: 'my-awesome-app',
    schema: appsync.Schema.fromAsset('graphql/schema.graphql'),
    });
    // Prints out the AppSync GraphQL endpoint to the terminal
    new cdk.CfnOutput(this, "GraphQLAPIURL", {
    value: api.graphqlUrl
    });
    }
    }

    View Slide

  85. Ok, but the app needs
    to be real-time
    multi-cloud
    guru

    View Slide

  86. AWS AppSync lets you specify which part of your data should be
    available in a real-time manner using GraphQL Subscriptions.

    View Slide

  87. Real-time subscriptions
    type Subscription {
    addedPost: Post
    @aws_subscribe(mutations: ["addPost"])
    updatedPost: Post
    @aws_subscribe(mutations: ["updatePost"])
    deletedPost: Post
    @aws_subscribe(mutations: ["deletePost"])
    }

    View Slide

  88. And it needs to be scalable!
    multi-cloud
    guru

    View Slide

  89. View Slide

  90. But what if you need
    a search functionality?
    multi-cloud
    guru

    View Slide

  91. AWS AppSync supports Amazon Elasticsearch!
    the GraphQL operations can be simple lookups,
    complex queries & mappings, fu! text searches,
    fuzzy/keyword searches or geo lookups.

    View Slide

  92. But what if you need to
    connect to an existing app?
    multi-cloud
    guru

    View Slide

  93. You can connect AWS AppSync to AWS Lambda!

    View Slide

  94. What about
    roles and permissions?
    multi-cloud
    guru

    View Slide

  95. • API_KEY Authorization
    • AWS_IAM Authorization
    • OPENID_CONNECT Authorization
    • AMAZON_COGNITO_USER_POOLS Authorization

    View Slide

  96. Multi-tenant?
    multi-cloud
    guru

    View Slide

  97. You can use Cognito Groups.

    View Slide

  98. use Resolver
    Mapping Template
    For fine-grained permissions

    View Slide

  99. ?
    multi-cloud
    guru

    View Slide

  100. ?

    View Slide

  101. You can use Apache Velocity Template Language (VTL)

    View Slide

  102. What's VTL?

    View Slide

  103. I would say it’s an alien language (we!, its Java-based)
    hard to test in isolation in a serverless application, especia!y
    in AWS CloudForamation.

    View Slide

  104. Alien language a.k.a. VTL
    #if($context.result["Owner"] == $context.identity.username)
    $utils.toJson($context.result)
    #else
    $utils.unauthorized()
    #end

    View Slide

  105. How do you test that?
    multi-cloud
    guru

    View Slide

  106. Testing Alien language Templates
    import { AppSyncMockFile } from 'amplify-appsync-simulator'
    import { VelocityTemplate } from 'amplify-appsync-simulator/lib/velocity'
    import { readFileSync } from 'fs'
    import { join } from 'path'
    import { getAppSyncSimulator } from './helpers/get-appsync-simulator'
    import { getVelocityRendererParams } from './helpers/get-velocity-renderer-params'
    // Read the VTL file from the disc
    const vtl = readFileSync(join(__dirname, '..', 'get-company-resolver-request.vtl'), 'utf8')
    const template: AppSyncMockFile = { content: vtl }
    // Create a simulator instance
    const simulator = getAppSyncSimulator()
    // Create a VelocityTemplate instance
    const velocity = new VelocityTemplate(template, simulator)

    View Slide

  107. Testing Alien language Templates
    describe('some-file.vtl', () => {
    const { ctxValues, requestContext, info } = getVelocityRendererParams('username', {
    'custom:companyId': 'company',
    })
    test('should render a template', () => {
    const result = velocity.render(ctxValues, requestContext, info)
    expect(result).toEqual({
    errors: [],
    isReturn: false,
    stash: {},
    result: {
    version: '2018-05-29',
    operation: 'GetItem',
    key: {
    id: { S: 'company' },
    },
    },
    })
    })
    })

    View Slide

  108. Ha! I don't like that!
    multi-cloud
    guru

    View Slide

  109. Me neither!

    View Slide

  110. AppSync supports Direct Lambda Resolvers,
    which skips VTL completely

    View Slide

  111. But what if you want
    to reuse some logic?
    multi-cloud
    guru

    View Slide

  112. You can do that in AWS Lambda or use Pipeline Resolvers

    View Slide

  113. Ok, ok, but this is still
    complex for the frontend
    multi-cloud
    guru

    View Slide

  114. AWS Amplify gives us nice libraries for the frontend

    View Slide

  115. And it can automatica!y generate queries, mutations,
    subscriptions and types for us!

    View Slide

  116. I give up!
    multi-cloud
    guru

    View Slide

  117. But this is not a!!

    View Slide

  118. AppSync supports caching and offline data synchronization

    View Slide

  119. Ok, but how do you test it?
    multi-cloud
    guru

    View Slide

  120. It depends on your approach.
    It's good to have end-to-end tests, but you can test your
    Lambda code or VTL templates in isolation.

    View Slide

  121. You can also run the app loca!y using AWS Amplify

    View Slide

  122. What if we need to use more
    complex architecture,
    i.e. CQRS
    multi-cloud
    guru

    View Slide

  123. Mutation Event storage
    Subscription
    Query
    Read-only table
    EventBridge
    Business logic Business logic

    View Slide

  124. Mutation Event storage
    Subscription
    Query
    Read-only table
    EventBridge
    Business logic Business logic

    View Slide

  125. Mutation Event storage
    Subscription
    Query
    Read-only table
    EventBridge
    Business logic Business logic

    View Slide

  126. multi-cloud
    guru

    View Slide

  127. View Slide

  128. Serverless
    GraphQL Guru

    View Slide

  129. View Slide

  130. Quick Summary:
    • GraphQL makes your frontend and backend
    connection effortless
    • AppSync makes GraphQL management effortless
    • Serverless GraphQL makes you a super hero

    View Slide

  131. @slobodan_
    vacationtracker.io

    View Slide