0% found this document useful (0 votes)
21 views

Azure Functions Part 1

The document provides details about an Azure Functions course including the lecturer, course content, assignments, and projects. The course will cover building applications and workflows using Azure Functions including triggers, bindings, and chaining functions together. Students will complete a final project applying concepts like serverless architecture, microservices, and cloud databases.

Uploaded by

projectjr2 Profs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Azure Functions Part 1

The document provides details about an Azure Functions course including the lecturer, course content, assignments, and projects. The course will cover building applications and workflows using Azure Functions including triggers, bindings, and chaining functions together. Students will complete a final project applying concepts like serverless architecture, microservices, and cloud databases.

Uploaded by

projectjr2 Profs
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Azure Functions

Azure Functions : Course Details


• Course Details:
• Lecturer: Frank Dersjant
• Mail: [email protected]
• Lectures consist of theory, demo and Lab/Workshop + homework (highly recommended)
• Demo Source Code : https://github.com/frankdersjant/IntroAzureFunctions
• .NET 6.0 LTS Isolated/In Process
• Moodle Course: 2324 Inf/IT4.2 Cloud Computing
https://moodle.inholland.nl/course/view.php?id=21618&sectionid=6588
57#section-14

• Final Assignment – you will be graded!


• End Project combined with Azure Functions, Azure Data Storage, Web.Api (and/or/not Vue.js)
• Front end NOT mandatory

• We will BUILD stuff during the lectures.... (its really not that difficult)
Azure Functions: End Project
• End Project : you can choose between one of 2 projects
• Last year – one fail – average mark was quite high
Metric Points
Cloud Database Architecture:
The application is designed with scalability of data services in mind. 20

Resource allocation is dedicated to the appropriate service/data source 20

The deployment environment (local vs public, private cloud) is clearly 5


defined.

Capacity and cloud database use throughput have been considered 5


(eg table storage keys, shards etc)

N tier application
Consists of the Data Tier, Business Tier (service layer, validation and 5
business rules), presentation tier (not required)

Use of Azure functions (at least 2) 5

Loosely coupled
Services are independent 10

Services are testable (either through mocking or stubs) 10


CQRS:
Azure Functions: Course content
• What we will learn:
• Part 1
• Intro to Serverless and Microservices
• Azure functions: The Concept
• Azure functions: Triggers
• Azure Functions: DI

• Part 2
• Azure Functions: Bindings (Input and Output)
• Azure Functions: Pipelines aka Chaining
• Azure Functions: Durable Functions
• Azure Functions: Fan Out – Fan In ?
• Azure Function: Human Interaction? (background info)
• Azure Functions: Error Handling Tips and Do’s and Dont‘s (background info)
Serverless: Definition
• The current working definition of serverless is as follows:

"A service that abstracts away all server details, provides


reactive scaling to demand, and is charged on a resource-usage-
based payment model".

• Encompasses serverless databases and takes into account reactive scaling.

• Serverless fits use cases from simple web applications to massively scaled and complex
applications with millions of users.

You think of the server less!


Serverless-FAAS
• Key component in Serverless is Function-as-a-Service
• Idea: write the code – upload to cloud – all aspects are handled
there
• Serveless fits into the paradigma of Microservices: individual
components can scale up infinitely
• Difference between MS and AZ?
– AZ has only 1 task; MS can have multiple
– AZ: shortlived (low impact on CPU and memory); MS not so...
Azure Functions: How did we get here?

• Evolution from on premise (HW and SW) to PAAS (not


focusssed on HW and SW)
• PAAS requires VM’s – costly (50 euro per instance) and take
time to spin up
Azure Functions: Why???

• Small code base(lightweight); EASY to write thus easy to maintain


• Serverless ie you have to think about the server less...
• Scalable – basically “unlimitless” scalable
• Spin up quickly
• Language (and platform) agnostic – one team can write in golang and
another team in C# - AF will “talk” to each other
• CHEAP for instance: $2.00 per 2 million executions (compute on
demand)
• Lots of Jobs available (384 – dd 30-08-2023)
Microservices
• Split the functionality of an app into the smallest possible units
that can manage their own state
• Advantges: polyglot
CI and deployment are easier
Each team works on his function (pizza slice
principle)
Each service can scale independentely!
Difference between AZ and Microservices
• Microservices encompass larger, independently deployable
components of an application that communicate with each
other to provide comprehensive functionality.
Difference between AZ and Microservices
• Microservices are an architectual style that breaks monolithic apps into
specific independant business capability which are deployable as a stand
alone, most;y communication between each other (mostly) through API calls
• Azure Functions are more focused on individual task execution triggered by
events
• Microservices are larger in scope than individual Azure functions – eg
CustomerInfo system
• Microservices can have their own datastorage and logic
• Both AZ and Microservices can scale independantly from each other
depending on demand
Advantages of Azure functions
• Event-Driven: Azure Functions are designed to be triggered by events, such as HTTP requests, database changes, timer schedules, message queues,
and more. This event-driven approach allows you to build reactive and responsive applications that automatically execute code in response to specific
events.
• Auto-Scaling: Azure Functions can automatically scale based on the number of incoming requests or events. This ensures that your application can
handle varying levels of load without manual intervention.
• Micro-Billing: Azure Functions offer granular billing based on the execution time and memory usage of each function invocation. This allows you to
optimize costs by choosing the appropriate execution plan and resource allocation for each function.
• Quick Development: Azure Functions allow developers to focus on writing code for specific tasks or actions without dealing with the complexities of
infrastructure setup. This accelerates development cycles and reduces time-to-market.
• Language Flexibility: Azure Functions supports multiple programming languages, including C#, JavaScript, Python, PowerShell, and more. This flexibility
enables developers to work with their preferred language or the one most suited for the task.
• Stateless Execution: Azure Functions are designed to be stateless, meaning they don't maintain persistent state between invocations. This encourages
writing functions that are modular, easier to test, and less prone to bugs related to shared state.
• Scalable Logic: While Azure Functions are often associated with simple tasks, they can also be used to build complex workflows by chaining multiple
functions together. This allows you to create intricate business logic in a scalable manner.
• Built-In Triggers and Bindings: Azure Functions provide built-in triggers (events that start the function) and bindings (connections to data sources or
services) that simplify working with external resources and services.
• DevOps Integration: Azure Functions can be integrated into a DevOps pipeline, enabling automated testing, deployment, and monitoring practices for
efficient software delivery.
• Hybrid Scenarios: Azure Functions can be deployed in both the cloud and on-premises environments, allowing you to build hybrid applications that
span multiple deployment
Advantages of Microservices
• Scalability: Microservices allow for independent scaling of individual services based on their specific demands. This fine-grained scalability
ensures efficient resource utilization and responsiveness to varying levels of load.
• Modularity and Flexibility: Services in a microservices architecture are independent and loosely coupled.
• Faster Development and Deployment: With smaller, focused services, development teams can work more efficiently. faster cycles and
reduced time-to-market.
• Technology Heterogeneity: Each microservice can be developed using the most appropriate technology stack for its specific task. This
flexibility allows for the use of different programming languages, databases, frameworks, and tools within the same application.
• Fault Isolation: Since microservices are isolated from each other, a failure in one service is less likely to impact the entire application. Fault
isolation helps maintain the overall availability and reliability of the system.
• Improved Resilience: Microservices architecture encourages redundancy and graceful degradation. If one service fails, the rest of the
application can continue to function, albeit with reduced capabilities.
• Scalable Development: Microservices allow organizations to scale development efforts by breaking down large and complex projects into
smaller, manageable pieces that can be worked on by smaller teams.
• Enhanced Fault Tolerance: Microservices can be designed to handle failures gracefully by implementing retry mechanisms, fallbacks, and
redundancy. This improves the overall robustness of the application.
• Easier Adoption of New Technologies: As technology evolves, you can adopt new tools and technologies for specific services without
requiring a complete overhaul of the entire application.
• Economical Resource Utilization: By scaling and allocating resources only to the services that need them, you can achieve better resource
utilization and cost efficiency.
Where do we find Azure Functions
• Webhooks and APIs: Azure Functions are great for building lightweight APIs and webhooks. You can create functions that respond to HTTP requests and perform specific actions, such
as processing data, sending notifications, or updating databases.
• Data Processing and ETL: Use Azure Functions to process and transform data in real-time or on a schedule. This can include data validation, enrichment, filtering, and loading data
into data warehouses or databases.
• Real-Time Analytics: You can use Azure Functions to process incoming data streams, perform aggregations, and generate real-time analytics insights. This is particularly useful for
applications that require up-to-the-moment insights.
• File Processing: Functions can be triggered when files are uploaded to cloud storage, allowing you to automatically process, transform, or analyze the contents of the files. This is
useful for scenarios like image resizing, file validation, or data extraction from uploaded files.
• Event Processing: Process events from IoT devices, sensors, or event hubs. Azure Functions can ingest, analyze, and respond to events in real-time, allowing you to trigger actions
based on certain conditions being met.
• Chatbots and Conversational Interfaces: You can use Azure Functions to power chatbots and conversational interfaces. Functions can process messages from users, interpret intents,
and provide appropriate responses.
• Integration and Orchestration: Azure Functions can act as glue code to integrate different services and systems. They can receive events from one service, perform transformations,
and then send data to another service.
• Automated Workflows: Build automated workflows by chaining together multiple functions. Each function can perform a specific task in the overall workflow, enabling complex
business processes.
• Scheduled Tasks: Use Azure Functions to execute tasks at specified intervals using timers. This can include tasks like sending regular reports, triggering data backups, or performing
maintenance operations.
• IoT Data Ingestion: Azure Functions can ingest data from IoT devices, preprocess it, and store it in databases or data lakes for further analysis.
• Authentication and Authorization: Azure Functions can integrate with authentication and authorization services to secure API endpoints, ensuring that only authorized users or
applications can access certain functionality.
• Image and Video Processing: Functions can be used for tasks like image or video analysis, such as detecting objects, faces, or generating thumbnail images.
• Automated Notifications: Trigger functions to send notifications via email, SMS, or other communication channels in response to certain events or conditions.
• Serverless Backend for Mobile Apps: Use Azure Functions as the backend for mobile apps to handle user authentication, data synchronization, and other backend services without
the need to manage servers.
Azure Functions: The case for

• Yes!!
• Event driven workloads (to respond to events, such as HTTP requests, database changes, incoming messages, or timers.
Execute code in response to these events without the need to manage underlying infrastructure.
• POC
• Task scheduling
• IoT stuff

• Nooooooo!!
• No replacement for Web Api’s – long running processes
• Consistent Workloads – cost effective?
• Resource-Intensive Tasks: designed to be lightweight and stateless
• Complex State Management: app requires complex state management between function invocations, Azure Functions'
stateless nature might not be suitable. Consider using Azure Durable Functions or Azure Logic apps.
Monolith to Serverless
Monolithic App example
Monolithic to Serverless Functions
“Functional Decomposition”
Azure functions – The Concept
• Monolithic architecture – break/decompose/extend pieces off
the monolithic app
• Eg: payment in FAAS – puts message in queue
• Message placed in queue – generate email
• Payment placed in table storage
• Generate report (nightly - timer)
Azure functions – The Concept
• Code: just one HTTP function (C#/java/javascript/node.js/whatev’s)
• Just code to respond to EVENT
• Describe EVENT which will trigger the function
• Events eg: timer event – run every 5 min
Data arrives – queue, storage
Http request
No boilerplate code
Automatic scaling
Azure functions – Offerings
Functions are a FAAS -App service plan (built on webjobs)
Offer: Integreted security (OAuth)
Simplified integration (eg Sendgrid)
Certificates, domains, Auth, CI/CD

• Allows you to focus on business requirements.


Azure Serverless: Demo business case
– Billing App -
Azure Serverless: Demo business case

• Billing Function App is a Timer Trigger azure function. It will execute every day.
• Billing Function app will charge all the active subscribers who have passed the
billing date.
• Based on the charge success/failure response, it pushes a message in email-msg-
queue. This will trigger the Email Sending Function App to notify the subscriber
about billing.
• Billing Function App will push the message in invoice-generation-queue to
complete the billing.
• Also, it will trigger the Invoice Generation Function, and it will generate invoice
reports. Email Sending Function App will send the invoice reports to the service
owner.
Azure Serverless: Demo business case
source: https://www.altkomsoftware.com/blog/azure-functions
Azure Serverless: Demo business case
• User uploads CSV file with Beneficiaries to a specific data storage – Azure Blob Container.
• The above action triggers a function GenerateBillingItemsFunc that is responsible for:
– generating billing items, which use prices from an external database – CosmosDB and saving them in the table –
Azure Table;
– sending message about the need to create a new invoice to Azure Queue;
• When a new message appears on the queue, next function is triggered (GenerateInvoiceFunc). This function creates
domain object Invoice and saves this object in database – CosmosDB. After successful save, it sends a message to two
Azure Queues.
• When a new message appears in one of queues, function PrintInvoiceFunc is triggered. This function uses external
engine to PDF generation – JsReport and saves PDF file in Azure Blob Storage.
• When a new message appears in the second queue, function NotifyInvoiceFunc is triggered. This function uses two
external systems – SendGrid to email sending and Twilio to SMS sending.
• We tried to create functions with the best practices, i.e. they would be small, simple and would work independently.

• NOTE – AZURE QUEUE is at the HEART of the Architecture!!!!!


• Just run small “pieces of code” - think a simple method – no
need for VM($$$)
• Serverless – just means you have to worry about the server less
• PAAS solution – Azure supplies the cloud infrastructure to run
(and scale) your code
• Call your function(method) with a triggered event, eg: http
request, incoming message, timer trigger, trigger on datastore
10 min Break
• Let’s get some coffee so that we can be hyperaware of how
little we are going to get done today....
Azure functions: Triggers
• How does the function start? -> TRIGGER – usually an event
originationg from within an app
• Most common: Http request
• Http request: Post (or Get) to specific URI
• Timer : cron based expression eg run every hour
• Triggers based on Azure services (data operations): Blob /
Table, CosmosDB, Queue, SQL Server -> fires everytime record
mutated
Azure functions: Webhooks
• Webhooks: supplies other apps with real time data
• eg Github pull/push request can fire azure http request trigger
• Paypal
Azure Functions: HttpTrigger
HTTP trigger: FunctionAppWorldsSmallestAPI

• Note:
– FunctionName
– Authorizationlevel....
– Get and Post
– FunctionContext: Object that represents the context in which a function is executed, contains information about function
invocation, such as trigger details, invocation ID and logging capabilities
Azure Functions: Mini Workshop
(10 min)
• Build the Http triggered Azure Function as shown above
• Use .net 6.0 LTS in ISOLATED mode
• Test in Browser and/or Postman
Azure functions: Proposed Project Layout
Each Azure Function “lives” in its own project
Azure Functions: HttpTrigger
Deserilization

• Note: HttpRequestData req


• Use of StreamReader
• Customer customerdata = JsonSerializer.Deserialize<Customer>(requestBody);
Azure Functions: Timer trigger
Timer trigger: FunctionAppTimer

• NB!!! Requires local.settings.json

• Note: “cron like” way of timing -> hmmm where did I see this before?
• Timer fires every 1 minute
Azure Serverless: Azure Queue Storage
• Queue: KEY component in limitless scaling (truely loosley coupled architecture?)
• Characteristics:
FIFO
Point to Point communication
Async

Azure Queue Storage: closet “fit” to serverless/microservices (IMHO)

• Popular queues:
Azure Storage Queue
Event Hubs: Big Data event streaming service - milj messages p/s – (IOT)
Event Grids: managed event routing – real or near real time services
Azure Service Bus: message broker (intermediary program module that
translates a message from messaging protocol of the sender to the messaging
protocol of the receiver. (wiki)
Azure Functions: Queue trigger
• Queue trigger: FunctionAppQueueDemo
• Add to queue in Storage explorer:

• NB: local.settings.json
Azure Functions: Queue trigger (contd.)

• Note: QueueTrigger – trigger will fire on the queue “myqueue”


• Azure Queue is NOT meant to be a long term “storage”
• QueueMessage – objects might be better IMHO
Azure Functions: Queue trigger (contd.)
• Output:

• Item is “dequeued”
Azure Functions: Mini Workshop Queue
(10 min)
• Download and install Microsoft Azure Storage Explorer
• Create a queue in the (local) Emulator - called “myqueue”
• Create Queuetriggered Azure Function which references
“myqueue”
• Insert an item into the Queue and check that trigger is fired
• Is the item dequeued?
10 min Break
• Lets get some coffee and NOT talk about programming or code

Azure Functions: Dependency injection
• DI: object receives dependant object through injection (mostly
ctor injection)
• injecting services, ideal for writing N-tiers layers, and unit tests
(esp. “mocking”)
• Registering of Dependencies is done in Programs.cs eg:
Azure Functions: Dependency injection
Demo
• AzureFunctionDependencyInjection
• Steps: NB: remove static in class def
• Register services in Program.cs
• Note:
FakeDB : “database” faked as a List!!
Azure Functions Mini Workshop
(est. time 30 - 45min)
• Design app conform N-Tier architecture
• Business layer contains Order (prop’s OrderId, OrderName)
• Create IOrderRepo with Create and getOrder methods
• Create IOrderService which implements the OrderRepo
• Implement dependency injection
• Implement Azure functions to get all Orders and add a Order to
the Repo (List)
DI and IOC
• Azure Functions DI allow N-tier architecture
• Building of loosely coupled applications
• Allows for Unit testing
Azure Functions: Demo code
• https://github.com/asc-lab/azure-functions-billing

• https://github.com/chsakell/azure-functions-proxies

You might also like