Talks

Building modern web-applications with GraphQL & serverless Ruby

Building modern web-applications with GraphQL & serverless Ruby

by Marion Schleifer

In this presentation, Marion Schleifer discusses building modern web applications using GraphQL and serverless architecture with Ruby. Highlighted at Ruby Day 2019, the talk primarily focuses on leveraging the Hasura GraphQL engine as a serverless backend. The agenda includes:

  • Introduction to the Speaker: Marion Schleifer shares her background as a community organizer, freelance developer, and motocross mechanic, conveying her enthusiasm for technical talks.

  • Understanding the Three-Factor Application Architecture: A new architecture for serverless applications proposed by Hasura, emphasizing high feature velocity and scalability. The three factors are:

    • Real-time GraphQL access designed for low-latency data retrieval.
    • Reliable eventing that ensures events are sent to clients upon database changes.
    • Serverless architecture that allows for flexible business logic deployment in the cloud.
  • Comparison of GraphQL and REST: Marion illustrates the differences between REST and GraphQL, specifically how GraphQL's single endpoint for data requests simplifies interaction for front-end developers, thus avoiding common issues in REST like over-fetching or under-fetching data.

  • Creating a Sample Harry Potter API: The talk includes an engaging case study where a Harry Potter API is built using Hasura. Steps include setting up a Postgres database, creating relational tables, and writing queries and mutations.

  • Real-time Capabilities and Subscriptions: Implementation of subscriptions for dynamic updates is highlighted, showcasing how they enhance user experience by providing immediate data without refreshing.

  • Integration with a Vue.js Frontend: Guide on connecting the Hasura backend with a Vue frontend using Apollo Client demonstrates how data interaction can be streamlined while maintaining real-time functionality.

  • Serverless Functions with Ruby: Marion discusses the role of serverless functions in cloud environments, particularly how they can be triggered by events and integrated effectively with Hasura, allowing developers to use Ruby for backend logic.

  • Community and Documentation: The presentation ends with insights into the supportive community around GraphQL and Hasura, mentioning available resources like documentation and Discord for user engagement.

In conclusion, the session emphasizes the efficiency and flexibility provided by combining GraphQL with Hasura, making it an attractive solution for developers looking to modernize their web applications while still utilizing familiar technologies like Ruby.

00:00:16.360 I am very happy to be here because, three years ago at Ruby Day, I did my first ever conference talk about learning to program using Ruby. I had done some other talks in the meantime, including a TEDx talk, but no technical talks. So, I am very happy to be back three years later with my first technical talk.
00:00:28.040 Today, I want to talk to you about the Hasura GraphQL engine and how to build modern serverless backends with it. First, let me introduce myself quickly.
00:00:39.860 By day, I am a community organizer in Zurich, running a few meetups. We are always looking for speakers, so if you're in the area, you are most welcome to join. I work as a freelance developer and advocate for Hasura, which allows me to engage in even more community activities. By night, I am a software developer and freelancer, working on various projects for different clients.
00:00:58.250 And on weekends—don’t laugh—I am a motocross mechanic, as my boyfriend is a professional motocross rider, and I am his mechanic. This offers a nice balance to the other things I do, allowing me to showcase my badass side that many people don’t know about. In fact, I'm currently reading the 450-page manual for our new bike. But enough about me; let's talk about today's agenda.
00:01:10.820 First, I want to introduce you to a new architecture called the three-factor app, which is used to build serverless applications. Then I will discuss GraphQL. How many of you are already working with GraphQL? Okay, for the others, it will be an introduction. After that, I will explain how to use GraphQL with Hasura and compare REST, which is a more traditional architecture, to the newer architecture with GraphQL. We will build a Harry Potter API—why Harry Potter? You will see later. This will include a brief excursion into connecting your Hasura backend to a Vue.js front-end. Finally, we will write some Ruby code by creating a serverless function in Ruby and discuss the GraphQL and Hasura community.
00:02:03.799 Now, let's get started with the three-factor app architecture. It is an architectural pattern for modern full-stack applications proposed by Hasura. This architecture should support high feature velocity and scalability, which we will explore shortly.
00:02:12.079 Traditionally, you have an application that communicates with an API layer, which retrieves data from a database while also interacting with several microservices. What do the three factors of the three-factor app mean? The first one is real-time GraphQL. It is designed to provide a simple and flexible workflow for front-end developers, meaning they can easily access the data without needing to request multiple endpoints from the backend.
00:02:29.330 With GraphQL, developers interact with just one endpoint, which allows for low latency. When accessing a resource, you want it to be instant. We avoid polling; instead, if something happens, an event is sent to the client, updating it in real-time.
00:02:46.490 The second factor is reliable eventing. Unlike traditional frameworks, which manipulate in-memory states, with GraphQL if a database mutation happens, an atomic event is sent to the client. This should be reliable; hence, every event that occurs should be delivered at least once.
00:03:02.150 The third factor involves facing serverless architecture. When the database structure is not sufficient and you need business logic, you will write it as event handlers or serverless functions, which can be deployed to any cloud provider such as Google Cloud or AWS. Importantly, the sequence of events doesn’t matter, meaning that it operates independently of a specific order.
00:03:14.120 Here again, we can compare the older architecture to the three-factor architecture. Now, the application talks to the real-time GraphQL API, which manages state through its event system, calling microservices, such as payment systems, in the cloud. We will make an example about this by the end of the talk.
00:03:30.230 What about GraphQL? You might have heard that many small and large companies are starting to switch to GraphQL. GraphQL is a typed query language, and I’m a fan of typing because it helps avoid errors.
00:03:44.030 You have a single endpoint for every resource in your database. This is the most crucial aspect: you request what you need and receive precisely that—no more, no less. If you only need the name of a person and not their email address, you get just the name. You can also gather fields from several resources in the same request, such as retrieving a person's profile along with their details in one go.
00:04:06.740 GraphQL simplifies the separation between the backend and front-end. Essentially, the entire backend operates with one endpoint, making it much easier for front-end developers to access database information.
00:04:20.310 GraphQL is gradually being adopted by more tech companies. Some large organizations, like Shopify, GitHub, and Twitter, are also shifting towards GraphQL.
00:04:37.180 An example from the GraphQL website demonstrates how to describe your data. For instance, a type object may include fields like name, tagline, and contributors. When you query for a project named 'GraphQL', you only request the tagline, not the name or contributors, and you receive exactly what you asked for.
00:04:53.580 You could build your own GraphQL server, but you don’t need to. Hasura serves as a GraphQL engine that allows for a backend and lets you make requests and create tables, functioning as a real-time GraphQL API. It’s open-source, so if you want to clone it and add your features, you can.
00:05:01.740 Hasura is essentially an HTTP API that queries Postgres using GraphQL. In the background, it interacts with a Postgres database while you write GraphQL queries for your data.
00:05:16.450 The system runs in a Docker container; you can deploy it to Heroku or cloud providers such as Google Cloud or AWS. If you have an existing Postgres database, you can utilize Hasura without needing to migrate everything at once, allowing for gradual migration.
00:05:32.260 Hasura supports various authentication types, such as JWT tokens and AWS Lambdas. It includes a management console that offers a UI for manually adding tables, data, and creating relationships.
00:05:46.430 The engine is written in Haskell, which contributes to its speed. Currently, Hasura is the fastest GraphQL engine available, largely attributed to its Haskell foundation.
00:06:02.370 Hasura began as an agency with client web application projects, leading them to develop their own engine due to their needs. Its open-source release came in June of last year after other companies showed interest in it.
00:06:25.680 Hasura aims for low latency; you should receive results without delays when querying resources. It also should handle numerous resources in a single query without consuming excessive CPU or memory.
00:06:39.520 Most projects will find this performance adequate initially but should consider alternatives when scaling up to large datasets or user bases.
00:07:01.120 Looking at the query lifecycle in Hasura, the first step is session resolution. Authorization occurs, and headers are analyzed. Next, incoming queries, which may seem like complex strings, are parsed to separate headers from body data.
00:07:17.080 The query is then validated for semantic correctness and whether the user has permission to access or modify any resources. Following this, the query is transformed into SQL since Postgres uses SQL as the underlying query language.
00:07:31.840 Data is extracted from the Postgres database, and finally, the result is sent back to the client as a GraphQL response. In my experience learning GraphQL, I initially used the Star Wars API, but since I'm not a fan, I created my own Harry Potter API for a more engaging experience.
00:07:48.260 We will build the beginning of this API, connecting data about movies and scenes. One movie has multiple scenes; characters and actors are linked similarly, establishing easy access between them, creating relationships like one-to-many or many-to-many.
00:08:02.550 We need to create a joint table to facilitate these many-to-many relationships for movies and characters within our API design. I will make this API available once I populate it with the necessary data, so you can learn from it without needing to use the Star Wars analogy.
00:08:19.880 Now let’s compare a more traditional REST architecture to GraphQL with serverless functionalities. In REST, each resource has its own endpoint. For instance, we have dedicated endpoints for movies, characters, actors, etc. Because of this, chaining endpoints can become quite complex.
00:08:34.620 In my experience in January, while working with a Rails API, the initial requirements were vague. They requested creation and deletion features, but as requirements evolved, it required considerable reworking of all the endpoints.
00:08:50.920 Using REST involves multiple HTTP methods like GET, POST, DELETE, and UPDATE, and you risk over-fetching or under-fetching data—requesting too much data using low resources or not getting the needed information.
00:09:06.780 In contrast, GraphQL operates through a single endpoint, utilizing GET and POST requests with Hasura. The endpoint is always the same, generally a POST request, ensuring you only receive the data you need.
00:09:21.650 If we want to list all Harry Potter movies, for instance, we simply access the /movies endpoint, akin to the index action in Rails. If we want to find characters for a specific movie, we query the corresponding endpoint with the movie's ID.
00:09:40.740 Now let’s see how to create a project with Hasura. To demonstrate, we will use Heroku, as it is quite simple and free. You won’t pay for Hasura itself, only for the cloud resources. Start the deployment process by naming your project uniquely.
00:09:58.450 Once you have set a name, the deployment will take some time. Meanwhile, you can look at the app’s template that will be deployed, showing the configuration settings, including the deployed Postgres add-on, indicating that the database will use PostgreSQL.
00:10:15.260 Once the project is ready, you can view the Hasura console at the designated endpoint, which serves as the single point for all your requests from front-end or other applications. The request headers will default to content type, making them easy to manage.
00:10:30.730 To create a table, simply navigate to the data section, selecting the option to create a table. For our new movie table, we will specify a UUID for every record and a title of type text and a release date.
00:10:44.700 In the same manner, you will define types mandatory for data querying. After defining the primary key, adding the table is a straightforward process.
00:10:58.400 Let’s populate the database with some initial data, which you can easily add via the console for testing purposes. You can check the browsed rows to verify that your data has been entered correctly, including the UUIDs created automatically.
00:11:15.170 Now we can start querying data from our newly created table. As a basic query demonstration, you will see that forming a query for movies can be as simple as defining the structure: query followed by the items you wish to fetch.
00:11:29.450 For instance, when querying for the title and release date of the movies, you should expect a structured response with the needed data. This capability allows you to easily aggregate data according to your application needs.
00:11:50.220 Let’s delve deeper into GraphQL relationships. For instance, we have a one-to-one relationship known as an object relationship, showcasing a character and its corresponding actor.
00:12:04.300 Next, there’s a one-to-many relationship; for example, a single movie has many scenes. We also encounter many-to-many relationships where we must create a joint table, as shown later in our exploration.
00:12:15.250 We will explore how to link actors to characters by modifying the characters table to include a column for the actor ID, which we will define as a UUID.
00:12:32.410 After adding the actor ID column, we need to declare it a foreign key, linking it back to the actors table. This efficiently establishes a relationship, assisting in organizing our query data effectively.
00:12:50.130 Now that we have this linkage in place, we can add an actor to an existing character and create a new query. For instance, we can request to see a list of characters along with their corresponding actor details.
00:13:08.860 As we run the query, we will analyze the results to ensure the connections between actors and characters are correctly represented within the output.
00:13:25.850 Next, we will not only read from the database using queries but also write to it using mutations. This involves adding, updating, or deleting our data entries.
00:13:46.580 For adding movies, we will use a mutation structure to define parameters. In GraphQL, if we mark a field as required with an exclamation mark, it dictates that the field must be populated.
00:14:01.240 A helper method provided by Hasura will facilitate the insertion of one or multiple movies at once through an array of objects, enabling bulk operations.
00:14:16.570 Upon triggering the mutation, we can check the database again to confirm that new entries appear, reflecting the functionality we’ve integrated.
00:14:38.510 To add real-time capabilities, we can implement subscriptions. Subscriptions allow our queries to send updates automatically when new data is inserted, maintaining current data without the need to refresh.
00:14:54.780 As subscriptions operate similarly to queries but with 'subscription' as the defining label, implementing them can enhance app responsiveness and user experience significantly.
00:15:12.490 With the subscription active, listing out current movies, adding a new entry, and witnessing an automatic update in your console will help illustrate this concept in action.
00:15:30.300 While managing permissions, you can set up various roles and access levels for your API routes. Granting your application admin rights allows full functionality, whereas restricting to a user role may limit actions to reading only.
00:15:47.940 When deploying securely, you need to manage access tokens and API keys. The Heroku console offers options for storing configuration variables, enabling you to define your access controls while developing.
00:16:02.900 By implementing a secure endpoint, you ensure that only authenticated users can execute operations—critical for maintaining data integrity.
00:16:17.790 Switching to a front-end framework like Vue, you can see how you connect your API backend seamlessly. Incorporating Apollo Client and HTTP links facilitates data interactions, streamlining your query process.
00:16:33.340 After configuring your Apollo Client to link to the Hasura backend, creating components to display data becomes more efficient. For instance, components for movie items and movie lists can fetch and render data using GraphQL effectively.
00:16:49.400 For each movie item, you can specify exactly which fields to display—like title and release date—making the structured data easily presentable within the Vue.js application.
00:17:02.960 By iterating through your movie list, the final output will showcase each movie with the data accurately pulled from the backend, illustrating how front-end and back-end integration works smoothly.
00:17:18.040 Also, using real-time updates retained by subscriptions enriches your application with instant feedback for user interactions, a vital feature in today’s applications.
00:17:34.320 Lastly, I wanted to cover Ruby and serverless functions. Serverless functions run in the cloud and can trigger events based on your application's actions, helping manage backend operations flexibly.
00:17:46.950 These functions are effective when paired with event triggers on Hasura, enabling you to invoke actions, such as sending emails when key events happen in the application.
00:18:00.590 For example, AWS has become the first cloud provider enabling Ruby support for serverless functions. This allows us to leverage Ruby for backend functions while benefiting from cloud efficiency.
00:18:17.570 Creating a new function via the AWS console requires specifying the name and defining the execution environment, allowing you to build features dynamically based on your application needs.
00:18:37.470 Upon defining your function, you can set up an API gateway to establish triggers that generate HTTP requests upon certain events, leading to seamless interactivity with your application logic.
00:18:54.630 Subsequently, successfully inserting a new movie into the database will trigger the corresponding event in the backend, sending necessary responses as defined within your function.
00:19:11.850 You can check the event console to verify that your function was invoked correctly upon an insert action, allowing you to monitor real-time interactions effectively.
00:19:28.540 As you can see, serverless functions provide robust capabilities to handle backend logic without investing time in server management, allowing you to focus more on developing features.
00:19:44.430 Now, as we conclude the technical portion, I’d like to shift focus to the incredible community surrounding GraphQL and Hasura. Their documentation offers comprehensive guides, with an active Discord channel where users can quickly get their questions answered.
00:19:58.770 With many people utilizing Hasura and contributing to the ecosystem, your questions are often met with rapid responses. Being open-source means you can access their GitHub repository for additional insights or suggested contributions—fostering continuous improvement.
00:20:12.790 In conclusion, GraphQL allows users to achieve quick and easy database access. Hasura facilitates setting everything up with ease compared to traditional REST endpoints.
00:20:25.740 This architecture enables seamless connections to your front end, simplifying development processes. For those interested in more complex business logic, consider serverless functions that provide great flexibility and low maintenance.
00:20:48.170 The community around Hasura is supportive and helpful, always ready to assist you with any inquiries, and remember, Harry Potter for the win.
00:21:08.740 Thank you for your attention! Keep in touch and feel free to reach out with any questions!