Build a serverless analytics application with Amazon Redshift and Amazon API Gateway
The real value of this pattern is not simply โserverless analytics,โ but replacing chatty, stateful query handling with an event-driven control plane. Redshiftโs Data API lets the front end submit SQL without holding a database connection open, while API Gateway and Lambda separate initiation from retrieval. That matters to practitioners because it turns slow analytical work into an asynchronous workflow, reducing connection management and making web delivery more predictable for department-facing reporting, dashboards, and ad hoc analysis.
The architectureโs key mechanism is a split between signaling and data transfer. WebSocket frames are used only to keep a lightweight bidirectional session and notify the client when the query finishes; REST then fetches the larger result set because WebSocket payloads are capped at 32 KB. EventBridge bridges the Data API completion event to a Lambda notifier, and DynamoDB tracks connection state and report topics. Practically, this avoids polling overhead and supports multiple concurrent reports on one page.
The design is strong on operational simplicity, but it is not a free pass on governance. Query text still originates from the client flow, so the safety of the system depends on keeping SQL scripts prebuilt and limiting them to read-only statements; once users can influence broader query logic, injection and abuse risks return. The broader significance is that serverless can improve responsiveness and maintenance, but only when the application accepts the constraints of asynchronous retrieval and tightly controlled inputs.
Serverless applications are a modernized way to perform analytics among business departments and engineering teams. Business teams can gain meaningful insights by simplifying their reporting through web applications and distributing it to a broader audience. Use cases can include the following:
- Dashboardingย โ A webpage consisting of tables and charts where each component can offer insights to a specific business department.
- Reporting and analysisย โ An application where you can trigger large analytical queries with dynamic inputs and then view or download the results.
- Management systemsย โ An application that provides a holistic view of the internal company resources and systems.
- ETL workflowsย โ A webpage where internal company individuals can trigger specific extract, transform, and load (ETL) workloads in a user-friendly environment with dynamic inputs.
- Data abstractionย โ Decouple and refactor underlying data structure and infrastructure.
- Ease of useย โ An application where you want to give a large set of user-controlled access to analytics without having to onboard each user to a technical platform. Query updates can be completed in an organized manner and maintenance has minimal overhead.
Event-driven model
Event-driven applications are increasingly popular among customers. Analytical reporting web applications can be implemented through an event-driven model. The applications run in response to events such as user actions and unpredictable query events. Decoupling the producer and consumer processes allows greater flexibility in application design and building decoupled processes. This design can be achieved with the Data API and API Gateway WebSocket and REST APIs. Both REST API calls and WebSocket establish communication between the client and the backend. Due to the popularity of REST, you may wonder why WebSockets are present and how they contribute to an event-driven design.What are WebSockets and why do we need them?
Unidirectional communication is customary when building analytical web solutions. In traditional environments, the client initiates a REST API call to run a query on the backend and either synchronously or asynchronously waits for the query to complete. The โwaitโ aspect is engineered to apply the concept ofย polling. Polling in this context is when the client doesnโt know when a backend process will complete. Therefore, the client will consistently make a request to the backend and check. What is the problem with polling? Main challenges include the following:- Increased traffic in your network bandwidthย โ A large number of users performing empty checks will impact your backend resources and doesnโt scale well.
- Cost usageย โ Empty requests donโt deliver any value to the business. You pay for the unnecessary cost of resources.
- Delayed responseย โ Polling is scheduled in time intervals. If the query is complete in-between these intervals, the user can only see the results after the next check. This delay impacts the user experience and, in some cases, may result in UI deadlocks.
Solution overview
In this post, we show how to create a serverless event-driven web application by querying with the Data API in the backend, establishing a bidirectional communication channel between the user and the backend with the WebSocket feature in API Gateway, and retrieving the results using its REST API feature.ย Instead of designing an application with long-running API calls, you can use the Data API. The Data API allows you to run SQL queries asynchronously, removing the need to hold long, persistent database connections. The web application is protected usingย Amazon Cognito, which is used to authenticate the users before they can utilize the web app and also authorize the REST API calls when made from the application. Other relevant AWS services in this solution includeย AWS Lambdaย andย Amazon EventBridge. Lambda is a serverless, event-driven compute resource that enables you to run code without provisioning or managing servers. EventBridge is a serverless event bus allowing you to build event-driven applications. The solution creates a lightweight WebSocket connection between the browser and the backend. When a user submits a request using WebSockets to the backend, a query is submitted to the Data API. When the query is complete, the Data API sends an event notification to EventBridge. EventBridge signals the system that the data is available and notifies the client. Afterwards, a REST API call is performed to retrieve the query results for the client to view. We have published this solution on theย AWS Samples GitHub repositoryย and will be referencing it during the rest of this post. The following architecture diagram highlights the end-to-end solution, which you can provision automatically withย AWS CloudFormationย templates run as part of the shell script with some parameter variables.
- A web application is provisioned onย AWS Amplify; the user needs to sign up first by providing their email and a password to access the site.
- The user verifies their credentials using a pin sent to their email. This step is mandatory for the user to then log in to the application and continue access to the other features of the application.
- After the user is signed up and verified, they can sign in to the application and requests data through their web or mobile clients with input parameters. This initiates a WebSocket connection in API Gateway. (Flow 1, 2)
- The connection request is handled by a Lambda function,ย
OnConnect, which initiates an asynchronous database query in Amazon Redshift using the Data API. The SQL query is taken from a SQL script inย Amazon Simple Storage Serviceย (Amazon S3) with dynamic input from the client. (Flow 3, 4, 6, 7) - In addition, theย
OnConnectย Lambda function stores the connection, statement identifier, and topic name in anย Amazon DynamoDBย database. The topic name is an extra parameter that can be used if users want to implement multiple reports on the same webpage. This allows the front end to map responses to the correct report. (Flow 3, 4, 5) - The Data API runs the query, mentioned in step 2. When the operation is complete, an event notification is sent to EventBridge. (Flow 8)
- EventBridge activates an event rule to redirect that event to another Lambda function,ย
SendMessage. (Flow 9) - Theย
SendMessageย function notifies the client that the SQL query is complete via API Gateway. (Flow 10, 11, 12) - After the notification is received, the client performs a REST API call (GET) to fetch the results. (Flow 13, 14, 15, 16)
- Theย
GetResultย function is triggered, which retrieves the SQL query result and returns it to the client. - The user is now able to view the results on the webpage.
- When clients disconnect from their browser, API Gateway automatically deletes the connection information from the DynamoDB table using theย
onDisconnectย function. (Flow 17, 18,19)
Prerequisites
Prior to deploying your event-driven web application, ensure you have the following:- An Amazon Redshift cluster in your AWS environmentย โ This is your backend data warehousing solution to run your analytical queries. For instructions to create your Amazon Redshift cluster, refer toย Getting started with Amazon Redshift.
- After you create your Amazon Redshift cluster, add theย
AmazonS3ReadOnlyAccessย permission to the associated clusterย AWS Identity and Access Managementย (IAM) role.
- After you create your Amazon Redshift cluster, add theย
- An S3 bucket that you have access toย โ The S3 bucket will be your object storage solution where you can store your SQL scripts. To create your S3 bucket, refer toย Create your first S3 bucket.
Deploy CloudFormation templates
The code associated to the design is available in the followingย GitHub repository. You can clone the repository inside anย AWS Cloud9ย environment in our AWS account. The AWS Cloud9 environment comes withย AWS Command Line Interfaceย (AWS CLI) installed, which is used to run the CloudFormation templates to set up the AWS infrastructure. Make sure that the jQuery library is installed; we use it to parse the JSON output during the run of the script.
- cognito-setup.yamlย โ Creates the Amazon Cognito user pool to web app client, which is used for authentication and protecting the REST API
- backend-setup.yamlย โ Creates all the required Lambda functions and the WebSocket and Rest APIs, and configures them on API Gateway
- webapp-setup.yamlย โ Creates the web application hosting using Amplify to connect and communicate with the WebSocket and Rest APIs.
- Download the sample DDL scriptย and upload it to an existing S3 bucket.
- Change the IAM role value to your Amazon Redshift clusterโs IAM role with permissions toย
AmazonS3ReadOnlyAccess.
- Download the sample query scriptย and upload it to an existing S3 bucket.
- Upload the modified sample DDL script and the sample query script into a preexisting S3 bucket that you own, and note down the S3 URI path.
- Editย theย
script.shย file before you run it and set the values for the following parameters:
-
- RedshiftClusterEndpoint (aws_redshift_cluster_ep)ย โ Your Amazon Redshift cluster endpoint available on theย AWS Management Console
- DBUsername (aws_dbuser_name)ย โ Your Amazon Redshift database user name
- DDBTableName (aws_ddbtable_name)ย โ The name of your DynamoDB table name that will be created
- WebsocketEndpointSSMParameterName (aws_wsep_param_name)ย โ The parameter name that stores the WebSocket endpoint inย AWS Systems Manager Parameter Store.
- RestApiEndpointSSMParameterName (aws_rapiep_param_name)ย โ The parameter name that stores the REST API endpoint in Parameter Store.
- DDLScriptS3Path (aws_ddl_script_path)ย โ The S3 URI to the DDL script that you uploaded.
- QueryScriptS3Path (aws_query_script_path)ย โ The S3 URI to the query script that you uploaded.
- AWSRegion (aws_region)ย โ The Region where the AWS infrastructure is being set up.
- CognitoPoolName (aws_user_pool_name)ย โ The name you want to give to your Amazon Cognito user pool
- ClientAppName (aws_client_app_name)ย โ The name of the client app to be configured for the web app to handle the user authentication for the users
- Run the script using the following command:
./script.sh
SetupRedshiftLambdaFunction, which sets up an Amazon Redshift database table and populates data into the table. The following diagram illustrates this process.
Use the demo app
When the shell script is complete, you can start interacting with the demo web app:- On the Amplify console, underย All appsย in the navigation pane, chooseย DemoApp.
- Chooseย Run build.
- When itโs complete, use the URL provided to access the web application.
- Chooseย Sign Up.
- Forย Email ID, enter an email.
- Forย Password, enter a password that is at least eight characters long, has at least one uppercase and lowercase letter, at least one number, and at least one special character.
- Chooseย Letโs Enroll.
- Enter your email and the verification code sent to the email you specified.
- Chooseย Verify.
- Sign in using your credentials.
demoPage.htmlย website.
- Chooseย Open Connection.
- Forย Trip Month, specify a month (for this example, December) and chooseย Submit.
- When youโre done, chooseย Close Connectionย to close the WebSocket connection.
Clean up
To clean up your resources, complete the following steps:- On the Amazon S3 console, navigate to the S3 bucket containing the sample DDL script and query script and delete them from the bucket.
- On the Amazon Redshift console, navigate to your Amazon Redshift cluster and delete the data you copied over from the sample DDL script.
- Runย
truncate nyc_yellow_taxi; - Runย
drop table nyc_yellow_taxi;
- Runย
- On the AWS CloudFormation console, navigate to the CloudFormation stacks and chooseย Delete. Delete the stacks in the following order:
WebappSetupBackendSetupCognitoSetup
Monitoring
You can monitor your event-driven web application events, user activity, and API usage withย Amazon CloudWatchย andย AWS CloudTrail. Most areas of this solution already have logging enabled. To view your API Gateway logs, you canย turn on CloudWatch Logs. Lambda comes with default logging and monitoring and can beย accessed with CloudWatch.Security
You can secure access to the application using Amazon Cognito, which is a developer-centric and cost-effective customer authentication, authorization, and user management solution. It provides both identity store and federation options that can scale easily. Amazon Cognito supports logins with social identity providers and SAML or OIDC-based identity providers, and supports various compliance standards. It operates on open identity standards (OAuth2.0, SAML 2.0, and OpenID Connect). You can also integrate it with API Gateway to authenticate and authorize the REST API calls either using the Amazon Cognito client app or a Lambda function.Considerations
The nature of this application includes a front-end client initializing SQL queries to Amazon Redshift. An important component to consider are potential malicious activities that the client can perform, such as SQL injections. With the current implementation, that is not possible. In this solution, the SQL queries preexist in your AWS environment and are DQL statements (they donโt alter the data or structure). However, as you develop this application to fit your business, you should evaluate these areas of risk. AWS offers a variety of security services to help you secure your workloads and applications in the cloud, includingย AWS Shield,ย AWS Network Firewall,ย AWS Web Application Firewall, and more. For more information and a full list, refer toย Security, Identity, and Compliance on AWS.Cost optimization
The AWS services that the CloudFormation templates provision in this solution are all serverless. In terms of cost optimization, you only pay for what you use. This model also allows you to scale without manual intervention. Review the following pages to determine the associated pricing for each service:- Amazon API Gateway pricing
- AWS Lambda pricing
- Amazon EventBridge pricing
- Amazon S3 pricing
- Amazon DynamoDB pricing
- AWS Amplify pricing
- Amazon Cognito pricing
Conclusion
In this post, we showed you how to create an event-driven application using the Amazon Redshift Data API and API Gateway WebSocket and REST APIs. The solution helps you build data analytical web applications in an event-driven architecture, decouple your application, optimize long-running database queries processes, and avoid unnecessary polling requests between the client and the backend. You also used severless technologies, API Gateway, Lambda, DynamoDB, and EventBridge. You didnโt have to manage or provision any servers throughout this process. This event-driven, serverless architecture offers greater extensibility and simplicity, making it easier to maintain and release new features. Adding new components or third-party products is also simplified. With the instructions in this post and the generic CloudFormation templates we provided, you can customize your own event-driven application tailored to your business. For feedback or contributions, we welcome you to contact us through theย AWS Samples GitHub Repositoryย byย creating an issue. Original PostEnjoyed this article? Sign up for our newsletter to receive regular insights and stay connected.
