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

Serverless Web API, Azure Functions

Serverless Web API, Azure Functions

At API Summit 2016 in Berlin, I will do a session about serverless web APIs and Azure Functions.

Rainer Stropek

November 22, 2016
Tweet

More Decks by Rainer Stropek

Other Decks in Technology

Transcript

  1. Saves the day. API Summit Serverless Rainer Stropek software architects

    gmbh http://www.timecockpit.com [email protected] @rstropek Web APIs Web Mail Twitter
  2. Your Host Rainer Stropek Developer, Entrepreneur MVP Microsoft Azure MVP

    Development Technologies MS Regional Director Senior Consultant IT-Visions Contact software architects gmbh [email protected] Twitter: @rstropek
  3. Agenda (German) DevOps schön und gut, aber welche Entwicklerinnen und

    Entwickler haben schon Lust auf Serverwartung? Statt PowerShell, Bash & Co zu lernen, will man sich auf seine eigentliche Entwicklungsarbeit konzentrieren. Serverless Computing will genau das bieten. Statt sich um Server oder Container zu kümmern, nutzt man Platform-as-a-Service (PaaS) Angebote in der Cloud. Sie bieten automatische Skalierung, Hochverfügbarkeit, Updates u.v.m. In dieser Session stellt Rainer Stropek, langjähriger Azure MVP und MS Regional Director, die Grundideen von Serverless Computing vor. Welche Vorteile gibt es? Wo sind die Grenzen? Anschließend zeigt Rainer live Demos mit Node.js und C# in Azure App Services her und berichtet über seine Erfahrungen, die er in der Praxis in den letzten Jahren damit gesammelt hat.
  4. What is „Serverless“? Aka Backend-as-a-Service or Function-as-a-Service Fully managed services

    Cloud is prerequisite See also Platform-as-a-Service (PaaS) Auto-scaling No explicit starting and stopping of VMs Done by the cloud provider automatically behind the scenes Billing not based on VM hours Abstract measures typically related to usage No usage  no costs (aka scale down to zero) See also Wikipedia
  5. Examples for FaaS Amazon Serverless Framework, AWS Lambda Supports Node.js,

    Python, Java (AWS FAQ) Microsoft Azure Functions (part of Azure App Service) Supports C#, F#, Node.js, Python, PHP , batch, bash, any executable (docs) Google Cloud Functions Supports Node.js (overview) Auth0 webtask Supports Node.js, C# (via Edge.js) (docs)
  6. Serverless High-level Architecture No servers but functions Pattern: Microservices Online

    editor or SCM integration Stateless (short-lived, ephemeral) Separate Auth service E.g. AAD, Google Auth API Gateway Routing, security Integration Hybrid solutions Event- or message-driven Webhooks (sync) Service bus, queues (async) Clients Auth Func 1 Func 2 Func … Gateway External System
  7. Patterns to Consider for FaaS… Combine FaaS with PaaS solutions

    (standard and custom) Don’t reinvent the wheel Examples: API Gateways, Search, RESTful web APIs from storage systems, etc. More logic on the client Especially compared to classical full-page-refresh web apps Higher-level functions using workflow engine Example: Azure Logic Apps Automate deployment using SCM integration Example: GitHub, VSTS
  8. More about Webhooks Wikipedia Examples Visual Studio Team Services Microsoft

    Office 365 GitHub Docker Hub Jira Slack Zendesk Dropbox Twilio
  9. Advantages and Challenges NoOps automation, managed service Reduce development costs

    Develop smaller components Reduce Operational costs No usage  no costs Designed for Microservices Handles fluctuating load Auto-scaling Support many languages/platforms Best tool for the specific job High degree of freedom for teams Deployment is harder Automation is a necessity Handling of breaking changes Troubleshooting is more difficult System-wide logging and telemetry is important Limited control over configuration Gets better with containers Proliferation Guidelines for practices and patterns necessary Economy of scope Not made for long-running tasks Startup latency Further readings: http://martinfowler.com/articles/serverless.html#benefits
  10. Demo Azure Functions Create Function App https://functions.azure.com/signin Function App Settings

    Create Function SCM integration C#, Webhook Online Testing Function App settings Trigger, Inputs, Outputs C#, Node.js HTTP , Service Bus Queues Fundamentals For more details see my GitHub repository
  11. HTTP Trigger using System.Net; public static async Task<HttpResponseMessage> Run(HttpRequestMessage req,

    TraceWriter log) { log.Info("Received Tic-Tac-Toe request"); var board = await req.Content.ReadAsAsync<string[]>(); if (board.Length != 9) { req.CreateResponse(HttpStatusCode.BadRequest, "No valid tic-tac-toe board"); } for(var row = 0; row < 3; row ++) { if (!string.IsNullOrWhiteSpace(board[row * 3]) && board[row * 3] == board[row * 3 + 1] && board[row * 3] == board[row * 3 + 2]) { return BuildResponse(req, board[row * 3]); } } for(var column = 0; column < 3; column ++) { if (!string.IsNullOrWhiteSpace(board[column]) && board[column] == board[3 + column] && board[column] == board[2 * 3 + column]) { return BuildResponse(req, board[column]); } } if (!string.IsNullOrWhiteSpace(board[0]) && board[0] == board[3 + 1] && board[0] == board[2 * 3 + 2]) { return BuildResponse(req, board[0]); } if (!string.IsNullOrWhiteSpace(board[2]) && board[2] == board[3 + 1] && board[2] == board[2 * 3]) { return BuildResponse(req, board[1]); } return BuildResponse(req); } private static HttpResponseMessage BuildResponse(HttpRequestMessage req, string winner = null) => req.CreateResponse(HttpStatusCode.OK, (winner == null) ? "No Winner" : $"Winner: {winner}"); C# Example
  12. HTTP Trigger module.exports = function (context, req) { // Parse

    request body var board = JSON.parse(req.body); // Make sure that body is a properly formed array if (Array.isArray(board) && board.length == 9) { // Body is ok -> send message to trigger analysis context.bindings.outputSbMsg = JSON.stringify({ Message: board }); // Send OK result to caller context.res = { status: 200 }; context.done(); } else { // Body is malformed -> send Bad Request to caller context.res = { status: 400, body: "No valid tic-tac-toe board" }; context.done(); } }; Node.js Example Multiple Outputs Service Bus Queue HTTP
  13. Queue Trigger #r "Newtonsoft.Json" using System; using System.Threading.Tasks; using Newtonsoft.Json;

    public class BoardMessage { public string[] Message { get; set; } } public static void Run(string boardMsg, TraceWriter log, out string outputSbMsg) { log.Info("Received Tic-Tac-Toe request"); var boardContent = JsonConvert.DeserializeObject<BoardMessage>(boardMsg); var board = boardContent.Message; if (board == null || board.Length != 9) { outputSbMsg = "No valid tic-tac-toe board"; return; } for(var row = 0; row < 3; row ++) { if (!string.IsNullOrWhiteSpace(board[row * 3]) && board[row * 3] == board[row * 3 + 1] && board[row * 3] == board[row * 3 + 2]) { outputSbMsg = BuildResponse(board[row * 3]); return; } } [...] outputSbMsg = BuildResponse(); } private static string BuildResponse(string winner = null) => (winner == null) ? "No Winner" : $"Winner: {winner}"; C# Example
  14. Scaling and Pricing Consumption plan Can run in other plans,

    too Price depends on: Memory Execution time Number of executions Quite high free grant Auto-scaling by Azure More about scaling: https://docs.microsoft.com/en- us/azure/azure-functions/functions-scale
  15. Summary No „Silver Bullet“ Is scalability necessary? We love it

    for jobs that run infrequently  huge cost saver App is stateless Other PaaS services for storing state are necessary We often use it together with App Service Hybrid Connections for on-prem data stores Should be part of an overall Microservice strategy Guidelines and practices are necessary Great to combine with other PaaS services Self-made or existing ones
  16. Saves the day. API Summit Q&A Rainer Stropek software architects

    gmbh [email protected] http://www.timecockpit.com @rstropek Thank your for coming! Mail Web Twitter