├── .env-example ├── .github └── workflows │ ├── delete_aws_resources.yml │ ├── initial_aws_ecs_build_workflow.yml │ └── main.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── img.jpeg ├── infrastructure ├── ecr_repository.yml ├── ecs_cluster.yml └── ecs_service.yml ├── realtime-poc ├── real_time_flow.py └── real_time_flow_with_slack_alert.py ├── requirements.txt └── task-definition.json /.env-example: -------------------------------------------------------------------------------- 1 | SLACK_WEBHOOK_URL=https://hooks.slack.com/services/xxx/xxx/xxx 2 | PREFECT_LOGGING_LEVEL=DEBUG 3 | PREFECT_API_URL=xxx 4 | PREFECT_API_KEY=xxx 5 | AWS_ACCESS_KEY_ID=xxx 6 | AWS_SECRET_ACCESS_KEY=xxx 7 | AWS_DEFAULT_REGION=us-east-1 8 | AWS_ACCOUNT_ID=123456789 -------------------------------------------------------------------------------- /.github/workflows/delete_aws_resources.yml: -------------------------------------------------------------------------------- 1 | name: Delete ECS Cluster, Prefect ECS Service and ECR repository 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | env: 7 | PROJECT: realtime-poc 8 | 9 | jobs: 10 | delete-stack: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v3 15 | 16 | - name: Configure AWS credentials 17 | uses: aws-actions/configure-aws-credentials@v1 18 | with: 19 | aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} 20 | aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} 21 | aws-region: ${{ secrets.AWS_DEFAULT_REGION }} 22 | 23 | - name: Delete ECR repository 24 | continue-on-error: true 25 | run: | 26 | aws ecr delete-repository --repository-name ${{ env.PROJECT }} --force 27 | aws cloudformation delete-stack --stack-name "${{ env.PROJECT }}-ecr" 28 | 29 | - name: Delete ECS agent service 30 | continue-on-error: true 31 | run: aws cloudformation delete-stack --stack-name ${{ env.PROJECT }} 32 | 33 | - name: All AWS resources deleted 34 | run: echo '### All AWS resources deleted! :tada:' >> $GITHUB_STEP_SUMMARY 35 | -------------------------------------------------------------------------------- /.github/workflows/initial_aws_ecs_build_workflow.yml: -------------------------------------------------------------------------------- 1 | name: Deploy Prefect Streaming Service to AWS ECS 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | cpu: 7 | description: CPU for the agent 8 | required: true 9 | default: '256' 10 | type: choice 11 | options: ['256', '512', '1024', '2048', '4096'] 12 | memory: 13 | description: Memory for the agent 14 | required: true 15 | default: '512' 16 | type: choice 17 | options: ['512', '1024', '2048', '4096', '5120', '6144', '7168', '8192'] 18 | 19 | env: 20 | PROJECT: realtime-poc 21 | ECS_CLUSTER: prefect-streaming 22 | 23 | jobs: 24 | ecr-repository: 25 | name: Create ECR repository 26 | runs-on: ubuntu-latest 27 | steps: 28 | - name: Checkout 29 | uses: actions/checkout@v3 30 | 31 | - name: Summary 32 | run: echo "### Workflow $GITHUB_WORKFLOW with GITHUB_SHA $GITHUB_SHA" >> $GITHUB_STEP_SUMMARY 33 | 34 | - name: Configure AWS credentials 35 | uses: aws-actions/configure-aws-credentials@v1 36 | with: 37 | aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} 38 | aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} 39 | aws-region: ${{ secrets.AWS_DEFAULT_REGION }} 40 | 41 | - name: Create new ECR repository using AWS CloudFormation 42 | uses: aws-actions/aws-cloudformation-github-deploy@v1 43 | with: 44 | name: "${{ env.PROJECT }}-ecr" 45 | template: infrastructure/ecr_repository.yml 46 | parameter-overrides: "RepositoryName=${{ env.PROJECT }}" 47 | no-fail-on-empty-changeset: "1" 48 | 49 | - name: ECR repository built 50 | run: echo "ECR repository built at $(date +'%Y-%m-%dT%H:%M:%S')" >> $GITHUB_STEP_SUMMARY 51 | 52 | prefect-streaming-service: 53 | name: Prefect Streaming ECS Service 54 | runs-on: ubuntu-latest 55 | needs: ecr-repository 56 | steps: 57 | - name: Checkout 58 | uses: actions/checkout@v3 59 | 60 | - name: Configure AWS credentials 61 | uses: aws-actions/configure-aws-credentials@v1 62 | with: 63 | aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} 64 | aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} 65 | aws-region: ${{ secrets.AWS_DEFAULT_REGION }} 66 | 67 | - name: Add Secrets to SSM Parameter Store (needed for container in ECS task) 68 | run: | 69 | aws ssm put-parameter --type SecureString --name PREFECT_API_URL --value ${{ secrets.PREFECT_API_URL}} --overwrite 70 | aws ssm put-parameter --type SecureString --name PREFECT_API_KEY --value ${{ secrets.PREFECT_API_KEY}} --overwrite 71 | # aws ssm put-parameter --type SecureString --name SLACK_WEBHOOK_URL --value ${{ secrets.SLACK_WEBHOOK_URL}} --overwrite 72 | 73 | - name: Login to Amazon ECR 74 | id: login-ecr 75 | uses: aws-actions/amazon-ecr-login@v1 76 | 77 | - name: Build, tag, and push image to Amazon ECR 78 | id: build-image 79 | env: 80 | ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} 81 | IMAGE_TAG: ${{ github.sha }} 82 | run: | 83 | docker build -t $ECR_REGISTRY/$PROJECT:$IMAGE_TAG . 84 | docker push $ECR_REGISTRY/$PROJECT:$IMAGE_TAG 85 | echo "::set-output name=image::$ECR_REGISTRY/$PROJECT:$IMAGE_TAG" 86 | 87 | - name: ECR image built 88 | run: echo "ECR image ${{ steps.build-image.outputs.image }} built at $(date +'%Y-%m-%dT%H:%M:%S')" >> $GITHUB_STEP_SUMMARY 89 | 90 | - name: Deploy to ECS with AWS CloudFormation 91 | uses: aws-actions/aws-cloudformation-github-deploy@v1 92 | with: 93 | name: ${{ env.PROJECT }} 94 | template: infrastructure/ecs_service.yml 95 | capabilities: CAPABILITY_NAMED_IAM 96 | parameter-overrides: "cpu=${{ github.event.inputs.cpu }},memory=${{ github.event.inputs.memory }},project=${{ env.PROJECT }},cluster=${{ env.ECS_CLUSTER }},image=${{ steps.build-image.outputs.image }},awsaccountid=${{ secrets.AWS_ACCOUNT_ID }},region=${{ secrets.AWS_DEFAULT_REGION }}" 97 | 98 | - name: ECS Service Deployment finished 99 | run: echo "ECS Service Deployment finished at $(date +'%Y-%m-%dT%H:%M:%S')" >> $GITHUB_STEP_SUMMARY 100 | 101 | - name: Generate task definition 102 | run: aws ecs describe-task-definition --task-definition ${{ env.PROJECT }} --query taskDefinition > task-definition.json 103 | 104 | - name: Upload task definition as artifact 105 | uses: actions/upload-artifact@v3 106 | with: 107 | name: ECS task definition 108 | path: task-definition.json 109 | 110 | - name: Summary 111 | run: echo '### AWS resources successfully deployed! :rocket:' >> $GITHUB_STEP_SUMMARY 112 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Real-time streaming Prefect flow on AWS ECS 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | env: 9 | PROJECT: realtime-poc 10 | ECS_CLUSTER: prefect-streaming 11 | ECS_TASK_DEFINITION: task-definition.json 12 | 13 | jobs: 14 | set_description: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v3 19 | - name: Generate Markdown Summary 20 | run: | 21 | echo "### Workflow $GITHUB_WORKFLOW with GITHUB_SHA $GITHUB_SHA" >> $GITHUB_STEP_SUMMARY 22 | echo "- **Changes**: detects changes in flow code and code dependencies as compared to the last commit" >> $GITHUB_STEP_SUMMARY 23 | echo "- **Build**: rebuilds Docker image and redeploys the service if any code dependencies changed
" >> $GITHUB_STEP_SUMMARY 24 | echo "Prefect streaming service gets deployed to AWS ECS Service ${{ env.ECS_CLUSTER }}/${{ env.PROJECT }} " >> $GITHUB_STEP_SUMMARY 25 | 26 | changes: 27 | name: Detect code changes 28 | runs-on: ubuntu-latest 29 | outputs: 30 | code_changed: ${{ steps.filter.outputs.code }} 31 | steps: 32 | - name: Checkout 33 | uses: actions/checkout@v3 34 | - uses: dorny/paths-filter@v2 35 | id: filter 36 | with: 37 | list-files: json 38 | filters: | 39 | code: 40 | - added|modified|deleted: 'realtime-poc/**' 41 | - added|modified|deleted: 'requirements.txt' 42 | - added|modified|deleted: 'Dockerfile' 43 | - added|modified|deleted: 'task-definition.json' 44 | - name: Generate Markdown Summary 45 | run: | 46 | echo "Changes as compared to the last commit" >> $GITHUB_STEP_SUMMARY 47 | echo ${{ steps.filter.outputs.code_files }} >> $GITHUB_STEP_SUMMARY 48 | 49 | ecr-ecs-build: 50 | needs: changes 51 | if: ${{ needs.changes.outputs.code_changed == 'true' }} 52 | runs-on: ubuntu-latest 53 | steps: 54 | - name: Checkout 55 | uses: actions/checkout@v3 56 | 57 | - name: Configure AWS credentials 58 | uses: aws-actions/configure-aws-credentials@v1 59 | with: 60 | aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} 61 | aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} 62 | aws-region: ${{ secrets.AWS_DEFAULT_REGION }} 63 | 64 | - name: Add Secrets to SSM Parameter Store (needed for container in ECS task) 65 | run: | 66 | aws ssm put-parameter --type SecureString --name PREFECT_API_URL --value ${{ secrets.PREFECT_API_URL}} --overwrite 67 | aws ssm put-parameter --type SecureString --name PREFECT_API_KEY --value ${{ secrets.PREFECT_API_KEY}} --overwrite 68 | # aws ssm put-parameter --type SecureString --name SLACK_WEBHOOK_URL --value ${{ secrets.SLACK_WEBHOOK_URL}} --overwrite 69 | 70 | - name: Login to Amazon ECR 71 | id: login-ecr 72 | uses: aws-actions/amazon-ecr-login@v1 73 | 74 | - name: Build, tag, and push image to Amazon ECR 75 | id: build-image 76 | env: 77 | ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }} 78 | IMAGE_TAG: ${{ github.sha }} 79 | run: | 80 | docker build -t $ECR_REGISTRY/$PROJECT:$IMAGE_TAG . 81 | docker push $ECR_REGISTRY/$PROJECT:$IMAGE_TAG 82 | echo "::set-output name=image::$ECR_REGISTRY/$PROJECT:$IMAGE_TAG" 83 | 84 | - name: Flow deployments finished 85 | run: echo "ECR image $ECR_REGISTRY/$PROJECT:$IMAGE_TAG built at $(date +'%Y-%m-%dT%H:%M:%S')" >> $GITHUB_STEP_SUMMARY 86 | 87 | - name: Fill in the new image ID in the Amazon ECS task definition 88 | id: task-def 89 | uses: aws-actions/amazon-ecs-render-task-definition@v1 90 | with: 91 | task-definition: ${{ env.ECS_TASK_DEFINITION }} 92 | container-name: ${{ env.PROJECT }} 93 | image: ${{ steps.build-image.outputs.image }} 94 | 95 | - name: Deploy Amazon ECS task definition 96 | uses: aws-actions/amazon-ecs-deploy-task-definition@v1 97 | with: 98 | task-definition: ${{ steps.task-def.outputs.task-definition }} 99 | service: ${{ env.ECS_CLUSTER }}/${{ env.PROJECT }} 100 | cluster: ${{ env.ECS_CLUSTER }} 101 | # wait-for-service-stability: true 102 | 103 | - name: Upload task definition as artifact 104 | uses: actions/upload-artifact@v3 105 | with: 106 | name: ECS task definition 107 | path: ${{ steps.task-def.outputs.task-definition }} 108 | 109 | - name: Summary 110 | run: echo '### AWS resources successfully redeployed! :rocket:' >> $GITHUB_STEP_SUMMARY 111 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | .tmp/ 132 | .idea/ 133 | .idea/inspectionProfiles/profiles_settings.xml 134 | .idea/inspectionProfiles/Project_Default.xml 135 | .idea/misc.xml 136 | .idea/modules.xml 137 | .idea/prefect-streaming.iml 138 | .idea/vcs.xml 139 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM prefecthq/prefect:2-python3.9 2 | COPY requirements.txt . 3 | RUN pip install -r requirements.txt 4 | COPY realtime-poc/ . 5 | CMD ["python", "real_time_flow.py"] 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # prefect-streaming 2 | Example project demonstrating deployment patterns for real-time streaming workflows 3 | 4 | Blog post: https://medium.com/the-prefect-blog/serverless-real-time-data-pipelines-on-aws-with-prefect-ecs-and-github-actions-1737c80da3f5 5 | 6 | ## Questions? 7 | 8 | Reach out via [Discourse](https://discourse.prefect.io/) or [Slack](https://prefect.io/slack) 9 | 10 | ![](img.jpeg) 11 | -------------------------------------------------------------------------------- /img.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anna-geller/prefect-streaming/768412a209ef2e7fe479f87509e427b44fe12141/img.jpeg -------------------------------------------------------------------------------- /infrastructure/ecr_repository.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: Create ECR repository and lifecycle policy 3 | Parameters: 4 | RepositoryName: 5 | Type: String 6 | Default: realtime-poc 7 | Resources: 8 | MyRepository: 9 | Type: AWS::ECR::Repository 10 | Properties: 11 | RepositoryName: !Ref RepositoryName 12 | LifecyclePolicy: 13 | LifecyclePolicyText: > 14 | { 15 | "rules": [ 16 | { 17 | "rulePriority": 1, 18 | "description": "Keep only one untagged image, expire all others", 19 | "selection": { 20 | "tagStatus": "untagged", 21 | "countType": "imageCountMoreThan", 22 | "countNumber": 1 23 | }, 24 | "action": { 25 | "type": "expire" 26 | } 27 | } 28 | ] 29 | } -------------------------------------------------------------------------------- /infrastructure/ecs_cluster.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | Description: Create ECS Fargate cluster 3 | Parameters: 4 | cluster: 5 | Type: String 6 | Description: Cluster name 7 | Default: prefect-streaming 8 | Resources: 9 | Cluster: 10 | Type: AWS::ECS::Cluster 11 | Properties: 12 | ClusterName: !Ref cluster 13 | -------------------------------------------------------------------------------- /infrastructure/ecs_service.yml: -------------------------------------------------------------------------------- 1 | AWSTemplateFormatVersion: 2010-09-09 2 | 3 | Description: > 4 | Creates a new AWS VPC. It then deploys an ECS task definition, required IAM roles, and ECS service 5 | running a Prefect Streaming Service in a subnet created within that VPC 6 | 7 | Parameters: 8 | cpu: 9 | Type: String 10 | Description: Allow Dynamic CPU configuration 11 | Default: 512 12 | AllowedValues: [256, 512, 1024, 2048, 4096] 13 | memory: 14 | Type: String 15 | Description: Allow Increasing Memory - from 8192 on requires 4096 CPU and increases in 1024 increments 16 | Default: 1024 17 | AllowedValues: [512, 1024, 2048, 4096, 5120, 6144, 7168, 8192 , 9216, 10240] 18 | project: 19 | Type: String 20 | Description: Project name 21 | Default: realtime-poc 22 | cluster: 23 | Type: String 24 | Description: ECS Cluster name 25 | Default: prefect-streaming 26 | awsaccountid: 27 | Type: String 28 | Description: AWS Account ID 29 | Default: 338306982838 30 | region: 31 | Type: String 32 | Description: AWS region name 33 | Default: us-east-1 34 | image: 35 | Type: String 36 | Description: Docker image for the service 37 | Default: prefecthq/prefect:2.0b8-python3.9 38 | 39 | Resources: 40 | PrefectFargateCluster: 41 | Type: AWS::ECS::Cluster 42 | Properties: 43 | ClusterName: !Ref cluster 44 | 45 | PrefectLogGroup: 46 | Type: AWS::Logs::LogGroup 47 | Properties: 48 | LogGroupName: !Ref project 49 | RetentionInDays: 7 50 | 51 | PrefectVPC: 52 | Type: AWS::EC2::VPC 53 | Properties: 54 | CidrBlock: 10.0.0.0/16 55 | EnableDnsSupport: true 56 | EnableDnsHostnames: true 57 | InternetGateway: 58 | Type: AWS::EC2::InternetGateway 59 | InternetGatewayAttachment: 60 | Type: AWS::EC2::VPCGatewayAttachment 61 | Properties: 62 | VpcId: !Ref PrefectVPC 63 | InternetGatewayId: !Ref InternetGateway 64 | PublicRouteTable: 65 | Type: AWS::EC2::RouteTable 66 | Properties: 67 | VpcId: !Ref PrefectVPC 68 | RouteToGateway: 69 | Type: AWS::EC2::Route 70 | DependsOn: InternetGatewayAttachment 71 | Properties: 72 | RouteTableId: !Ref PublicRouteTable 73 | DestinationCidrBlock: 0.0.0.0/0 74 | GatewayId: !Ref InternetGateway 75 | PrefectECSServiceSubnet: 76 | Type: AWS::EC2::Subnet 77 | Properties: 78 | VpcId: !Ref PrefectVPC 79 | CidrBlock: 10.0.0.0/16 80 | AvailabilityZone: 81 | Fn::Select: 82 | - 0 83 | - Fn::GetAZs: { Ref: 'AWS::Region' } 84 | MapPublicIpOnLaunch: true 85 | SubnetRouteTableAssociation: 86 | Type: AWS::EC2::SubnetRouteTableAssociation 87 | Properties: 88 | SubnetId: !Ref PrefectECSServiceSubnet 89 | RouteTableId: !Ref PublicRouteTable 90 | 91 | ExecutionRole: 92 | Type: AWS::IAM::Role 93 | Properties: 94 | RoleName: !Sub "${project}_ecs_execution_role" 95 | AssumeRolePolicyDocument: 96 | Version: 2012-10-17 97 | Statement: 98 | - Effect: Allow 99 | Principal: 100 | Service: ecs-tasks.amazonaws.com 101 | Action: sts:AssumeRole 102 | Policies: 103 | - PolicyName: AllowRetrievingSecretsFromParameterStore 104 | PolicyDocument: 105 | Version: 2012-10-17 106 | Statement: 107 | - Effect: Allow 108 | Action: 109 | - ssm:GetParameters 110 | Resource: "*" 111 | ManagedPolicyArns: 112 | - arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy 113 | 114 | TaskRole: 115 | Type: AWS::IAM::Role 116 | Properties: 117 | RoleName: !Sub "${project}_ecs_task_role" 118 | AssumeRolePolicyDocument: 119 | Version: 2012-10-17 120 | Statement: 121 | - Effect: Allow 122 | Principal: 123 | Service: ecs-tasks.amazonaws.com 124 | Action: sts:AssumeRole 125 | Policies: 126 | - PolicyName: PrefectAthenaS3DataLake 127 | PolicyDocument: 128 | Version: 2012-10-17 129 | Statement: 130 | - Effect: Allow 131 | Action: 132 | - athena:* 133 | - glue:* 134 | - s3:* 135 | Resource: "*" 136 | 137 | PrefectTaskDefinition: 138 | Type: AWS::ECS::TaskDefinition 139 | Properties: 140 | Family: !Ref project 141 | Cpu: !Ref cpu 142 | Memory: !Ref memory 143 | NetworkMode: awsvpc 144 | ExecutionRoleArn: !Ref ExecutionRole 145 | TaskRoleArn: !Ref TaskRole 146 | ContainerDefinitions: 147 | - Name: !Ref project 148 | Image: !Ref image 149 | LogConfiguration: 150 | LogDriver: awslogs 151 | Options: 152 | awslogs-region: !Ref AWS::Region 153 | awslogs-group: !Ref PrefectLogGroup 154 | awslogs-stream-prefix: !Ref project 155 | Secrets: 156 | - Name: PREFECT_API_URL 157 | ValueFrom: !Sub "arn:aws:ssm:${region}:${awsaccountid}:parameter/PREFECT_API_URL" 158 | - Name: PREFECT_API_KEY 159 | ValueFrom: !Sub "arn:aws:ssm:${region}:${awsaccountid}:parameter/PREFECT_API_KEY" 160 | # - Name: SLACK_WEBHOOK_URL 161 | # ValueFrom: !Sub "arn:aws:ssm:${region}:${awsaccountid}:parameter/SLACK_WEBHOOK_URL" 162 | RequiresCompatibilities: 163 | - FARGATE 164 | 165 | PrefectECSService: 166 | Type: AWS::ECS::Service 167 | DependsOn: 168 | - SubnetRouteTableAssociation 169 | - RouteToGateway 170 | - PrefectFargateCluster 171 | Properties: 172 | ServiceName: !Ref project 173 | Cluster: !Ref PrefectFargateCluster 174 | TaskDefinition: !Ref PrefectTaskDefinition 175 | DesiredCount: 1 176 | LaunchType: FARGATE 177 | NetworkConfiguration: 178 | AwsvpcConfiguration: 179 | AssignPublicIp: ENABLED 180 | Subnets: 181 | - !Ref PrefectECSServiceSubnet 182 | -------------------------------------------------------------------------------- /realtime-poc/real_time_flow.py: -------------------------------------------------------------------------------- 1 | import awswrangler as wr 2 | from datetime import datetime 3 | import pandas as pd 4 | import requests 5 | from typing import Any, Dict 6 | from prefect import task, flow, get_run_logger 7 | from prefect.blocks.system import String 8 | from prefect.task_runners import SequentialTaskRunner 9 | 10 | 11 | @task 12 | def extract_prices() -> Dict[str, Any]: 13 | url = ( 14 | "https://min-api.cryptocompare.com/data/pricemulti?" 15 | "fsyms=BTC,ETH,REP,DASH&tsyms=USD" 16 | ) 17 | response = requests.get(url) 18 | prices = response.json() 19 | logger = get_run_logger() 20 | logger.info("Received data: %s", prices) 21 | return prices 22 | 23 | 24 | @task 25 | def transform_prices(json_data: Dict[str, Any]) -> pd.DataFrame: 26 | df = pd.DataFrame(json_data) 27 | now = datetime.utcnow() 28 | logger = get_run_logger() 29 | logger.info("Adding a column TIME with current time: %s", now) 30 | df["TIME"] = now 31 | return df.reset_index(drop=True) 32 | 33 | 34 | @task 35 | def load_prices(df: pd.DataFrame) -> None: 36 | table_name = "crypto" 37 | wr.s3.to_parquet( 38 | df=df, 39 | path="s3://prefectdata/crypto/", 40 | dataset=True, 41 | mode="append", 42 | database="default", 43 | table=table_name, 44 | ) 45 | logger = get_run_logger() 46 | logger.info("Table %s in Athena data lake successfully updated 🚀", table_name) 47 | 48 | 49 | @flow(task_runner=SequentialTaskRunner(), retries=5, retry_delay_seconds=5) 50 | def real_time_flow(): 51 | # Real-time data pipeline 52 | raw_prices = extract_prices() 53 | transformed_data = transform_prices(raw_prices) 54 | load_prices(transformed_data) 55 | 56 | # Taking action in real-time 57 | thresh_value = float(String.load("price").value) 58 | curr_price = raw_prices.get("BTC").get("USD") 59 | logger = get_run_logger() 60 | if curr_price < thresh_value: 61 | message = f"ALERT: Price ({curr_price}) is below threshold ({thresh_value})!" 62 | logger.info(message) 63 | else: 64 | logger.info("Current price (%d) is too high. Skipping alert", curr_price) 65 | 66 | # logger.info("🚀 Real-time streaming workflows made easy! 🎉️ 🥳 🚀") 67 | 68 | 69 | if __name__ == "__main__": 70 | while True: 71 | real_time_flow() 72 | -------------------------------------------------------------------------------- /realtime-poc/real_time_flow_with_slack_alert.py: -------------------------------------------------------------------------------- 1 | import awswrangler as wr 2 | from datetime import datetime 3 | import pandas as pd 4 | from prefect import task, flow, get_run_logger 5 | from prefect.blocks.system import String 6 | from prefect.task_runners import SequentialTaskRunner 7 | import requests 8 | from typing import Any, Dict 9 | 10 | import os 11 | from prefect_slack import SlackWebhook 12 | from prefect_slack.messages import send_incoming_webhook_message 13 | 14 | 15 | @task 16 | def extract_prices() -> Dict[str, Any]: 17 | url = ( 18 | "https://min-api.cryptocompare.com/data/pricemulti?" 19 | "fsyms=BTC,ETH,REP,DASH&tsyms=USD" 20 | ) 21 | response = requests.get(url) 22 | prices = response.json() 23 | logger = get_run_logger() 24 | logger.info("Received data: %s", prices) 25 | return prices 26 | 27 | 28 | @task 29 | def transform_prices(json_data: Dict[str, Any]) -> pd.DataFrame: 30 | df = pd.DataFrame(json_data) 31 | now = datetime.utcnow() 32 | logger = get_run_logger() 33 | logger.info("Adding a column TIME with current time: %s", now) 34 | df["TIME"] = now 35 | return df.reset_index(drop=True) 36 | 37 | 38 | @task 39 | def load_prices(df: pd.DataFrame) -> None: 40 | table_name = "crypto" 41 | wr.s3.to_parquet( 42 | df=df, 43 | path="s3://prefectdata/crypto/", 44 | dataset=True, 45 | mode="append", 46 | database="default", 47 | table=table_name, 48 | ) 49 | logger = get_run_logger() 50 | logger.info("Table %s in Athena data lake successfully updated 🚀", table_name) 51 | 52 | 53 | @flow(task_runner=SequentialTaskRunner()) 54 | def real_time_flow(): 55 | # Real-time data pipeline 56 | raw_prices = extract_prices() 57 | transformed_data = transform_prices(raw_prices) 58 | load_prices(transformed_data) 59 | 60 | # Taking action in real-time 61 | thresh_value = float(String.load("price").value) 62 | curr_price = raw_prices.get("BTC").get("USD") 63 | logger = get_run_logger() 64 | if curr_price < thresh_value: 65 | message = f"ALERT: Price ({curr_price}) is below threshold ({thresh_value})!" 66 | logger.info(message) 67 | send_incoming_webhook_message( 68 | slack_webhook=SlackWebhook(os.environ["SLACK_WEBHOOK_URL"]), 69 | text=message, 70 | ) 71 | else: 72 | logger.info("Current price (%d) is too high. Skipping alert", curr_price) 73 | 74 | # logger.info("🚀 Real-time streaming workflows made easy! 🎉️ 🥳 🚀") 75 | 76 | 77 | if __name__ == "__main__": 78 | while True: 79 | real_time_flow() 80 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | awswrangler==2.16.1 2 | pandas==1.4.3 3 | prefect_slack==0.1.0 4 | requests==2.27.1 5 | -------------------------------------------------------------------------------- /task-definition.json: -------------------------------------------------------------------------------- 1 | { 2 | "containerDefinitions": [ 3 | { 4 | "name": "realtime-poc", 5 | "essential": true, 6 | "secrets": [ 7 | { 8 | "name": "PREFECT_API_URL", 9 | "valueFrom": "arn:aws:ssm:us-east-1:338306982838:parameter/PREFECT_API_URL" 10 | }, 11 | { 12 | "name": "PREFECT_API_KEY", 13 | "valueFrom": "arn:aws:ssm:us-east-1:338306982838:parameter/PREFECT_API_KEY" 14 | } 15 | ], 16 | "logConfiguration": { 17 | "logDriver": "awslogs", 18 | "options": { 19 | "awslogs-group": "realtime-poc", 20 | "awslogs-region": "us-east-1", 21 | "awslogs-stream-prefix": "realtime-poc" 22 | } 23 | } 24 | } 25 | ], 26 | "family": "realtime-poc", 27 | "taskRoleArn": "arn:aws:iam::338306982838:role/realtime-poc_ecs_task_role", 28 | "executionRoleArn": "arn:aws:iam::338306982838:role/realtime-poc_ecs_execution_role", 29 | "networkMode": "awsvpc", 30 | "requiresCompatibilities": [ 31 | "FARGATE" 32 | ], 33 | "cpu": "256", 34 | "memory": "512" 35 | } 36 | --------------------------------------------------------------------------------