<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Micaela Marrero on Medium]]></title>
        <description><![CDATA[Stories by Micaela Marrero on Medium]]></description>
        <link>https://medium.com/@micaelamarrero?source=rss-16ebc2ca22f6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*N48T3Z3He2Tc4zql7ayRRQ.png</url>
            <title>Stories by Micaela Marrero on Medium</title>
            <link>https://medium.com/@micaelamarrero?source=rss-16ebc2ca22f6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:48:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@micaelamarrero/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[CloudFront + Lambda Function URLs: Cómo crear APIs seguras sin API Gateway]]></title>
            <link>https://medium.com/@micaelamarrero/cloudfront-lambda-function-urls-c%C3%B3mo-crear-apis-seguras-sin-api-gateway-ee9a5110f84f?source=rss-16ebc2ca22f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee9a5110f84f</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Micaela Marrero]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 12:53:05 GMT</pubDate>
            <atom:updated>2025-09-29T13:42:43.035Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introducción:</strong></p><p>Las funciones Lambda de AWS son una herramienta muy interesante para ejecutar código de manera serverless. Su capacidad de escalar automáticamente, su modelo de pago por uso y su integración nativa con muchísimos servicios de AWS hacen que sea una de las opciones perfectas cuando pensamos en desplegar un servicio que nos ayude en tareas puntuales, procesamientos batch, APIs ligeras o microservicios.</p><p>Lambda puede ser invocada desde múltiples fuentes: S3, DynamoDB, EventBridge, SQS, SNS, y muchas más. Esta es una de las mayores ventajas.</p><p>Sin embargo, hasta hace poco, había un obstáculo: <strong>si necesitabas un endpoint HTTP para invocar tu función Lambda directamente, estabas obligado a usar API Gateway</strong>.</p><p>API Gateway es una excelente solución para APIs complejas con múltiples endpoints, autenticación, transformaciones de datos y más … pero para casos simples donde solo necesitas un endpoint básico, puede resultar excesivo y agregar latencia innecesaria.</p><p>Para solucionar este problema, AWS introdujo <strong>Lambda Function URLs</strong>, una característica que permite crear un endpoint HTTPS único y dedicado para invocar tu función Lambda directamente, sin necesidad de API Gateway.</p><p><strong>Lambda Function URLs nos ofrece:</strong></p><ul><li><strong>Simplicidad</strong>: Un endpoint directo sin configuraciones complejas.</li><li><strong>Latencia reducida</strong>: Sin las capas adicionales de API Gateway.</li><li><strong>Costo optimizado</strong>: Solo pagas por las invocaciones de Lambda.</li><li><strong>Flexibilidad de autenticación</strong>: Puedes usar autenticación IAM o configurarlo como público (NONE)</li></ul><p>El endpoint generado tiene esta forma:</p><pre>https://{url-id}.lambda-url.{region}.on.aws/</pre><p>Configurarlo es simple y desde terraform lo podemos hacer así:</p><pre>resource &quot;aws_lambda_function_url&quot; &quot;my_function_url&quot; {<br>  function_name      = aws_lambda_function.my_function.function_name<br>  authorization_type = &quot;NONE&quot;  # o &quot;AWS_IAM&quot;<br>}</pre><p>Pero acá surge otro problema: <strong>¿cómo protejo mi endpoint si no puedo usar autenticación IAM?</strong></p><p>Si tu función necesita ser accesible desde aplicaciones web, sistemas externos sin credenciales AWS, o simplemente queres evitar la complejidad de la autenticación IAM, entonces el tipo de autorización sera:&quot;NONE&quot;. Esto significa que tu endpoint está completamente público en internet.</p><p><strong>Una buena opción para solucionar esto es CloudFront como proxy de seguridad.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6HlVzWX65_3IQiSj7NbkQ.png" /></figure><p>Mi propuesta es usar <strong>CloudFront como una capa de protección</strong> delante de la Lambda Function URL. La idea es simple:</p><ol><li>CloudFront actúa como proxy hacia la Lambda.</li><li>Se genera un token secreto compartido entre CloudFront y Lambda.</li><li>CloudFront incluye este token en cada request como header personalizado.</li><li>Lambda valida el token y rechaza cualquier request que no lo incluya.</li><li>El endpoint público es el de CloudFront, no el de Lambda.</li></ol><p><strong>Implementación práctica (desde terraform):</strong></p><p>Primero, generamos un token secreto:</p><pre>resource &quot;random_string&quot; &quot;cloudfront_secret&quot; {<br>  length  = 32<br>  special = false<br>  upper   = true<br>  lower   = true<br>}</pre><p>Configuramos CloudFront para incluir el token como header:</p><pre>resource &quot;aws_cloudfront_distribution&quot; &quot;lambda_distribution&quot; {<br>  origin {<br>    domain_name = replace(aws_lambda_function_url.my_function_url.function_url, &quot;https://&quot;, &quot;&quot;)<br>    origin_id   = &quot;lambda-origin&quot;<br>    <br>    custom_origin_config {<br>      http_port              = 443<br>      https_port             = 443<br>      origin_protocol_policy = &quot;https-only&quot;<br>      origin_ssl_protocols   = [&quot;TLSv1.2&quot;]<br>    }<br>    <br>    custom_header {<br>      name  = &quot;x-origin-verify&quot;<br>      value = random_string.cloudfront_secret.result<br>    }<br>  }<br><br>  enabled = true<br>  aliases = [&quot;api.midominio.com&quot;] # ¡Recuerda reemplazar aca con tu dominio!<br><br>  default_cache_behavior {<br>    allowed_methods        = [&quot;DELETE&quot;, &quot;GET&quot;, &quot;HEAD&quot;, &quot;OPTIONS&quot;, &quot;PATCH&quot;, &quot;POST&quot;, &quot;PUT&quot;]<br>    cached_methods         = [&quot;GET&quot;, &quot;HEAD&quot;]<br>    target_origin_id       = &quot;lambda-origin&quot;<br>    compress               = true<br>    viewer_protocol_policy = &quot;redirect-to-https&quot;<br>    <br>    # Sin cache para APIs dinámicas<br>    cache_policy_id = &quot;4135ea2d-6df8-44a3-9df3-4b5a84be39ad&quot;<br>  }<br><br>  # Configuración SSL<br>  viewer_certificate {<br>    acm_certificate_arn = aws_acm_certificate.api_cert.arn # ¡Recuerda reemplazar aca con tu certificado!<br>    ssl_support_method  = &quot;sni-only&quot;<br>  }<br><br>  restrictions {<br>    geo_restriction {<br>      restriction_type = &quot;none&quot;<br>    }<br>  }<br>}</pre><pre>resource &quot;aws_lambda_function&quot; &quot;my_function&quot; {<br>  function_name = &quot;mi-api-handler-prod&quot;<br>  role          = aws_iam_role.lambda_exec_role.arn<br>  handler       = &quot;lambda_function.lambda_handler&quot;<br>  runtime       = &quot;python3.12&quot;<br>  timeout       = 60<br>  memory_size   = 256<br><br>  # ¡Recuerda reemplazar el nombre del bucket!<br>  s3_bucket = &quot;tu-bucket-de-codigo-lambda&quot;<br>  s3_key    = &quot;api/deployment.zip&quot;<br><br>  environment {<br>    variables = {<br>      # Inyectamos el secreto como variable de entorno<br>      CLOUDFRONT_SECRET = random_string.cloudfront_secret.result<br>    }<br>  }<br>}<br><br><br># --------------------------------------------------------------------------<br># Rol de IAM para la Ejecución de la Lambda <br># --------------------------------------------------------------------------<br><br>resource &quot;aws_iam_role&quot; &quot;lambda_exec_role&quot; {<br>  name = &quot;mi-api-lambda-execution-role&quot;<br><br>  # Política de confianza que permite a Lambda asumir este rol<br>  assume_role_policy = jsonencode({<br>    Version   = &quot;2012-10-17&quot;,<br>    Statement = [{<br>      Action    = &quot;sts:AssumeRole&quot;,<br>      Effect    = &quot;Allow&quot;,<br>      Principal = { Service = &quot;lambda.amazonaws.com&quot; }<br>    }]<br>  })<br>}<br><br># Política básica para que la Lambda pueda escribir logs en CloudWatch<br>resource &quot;aws_iam_role_policy_attachment&quot; &quot;lambda_logs&quot; {<br>  role       = aws_iam_role.lambda_exec_role.name<br>  policy_arn = &quot;arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole&quot;<br>}<br><br># --------------------------------------------------------------------------<br># Crear la URL pública para la Lambda (como vimos anteriormente)<br># --------------------------------------------------------------------------<br><br>resource &quot;aws_lambda_function_url&quot; &quot;my_function_url&quot; {<br>  function_name      = aws_lambda_function.my_function.function_name<br>  authorization_type = &quot;NONE&quot;<br>}</pre><p><em>Nota: Lo ideal seria que cada recurso de terraform se genere en archivos diferentes, y que se utilicen los modulos de terraform, pero a fines de este ejemplo se mantiene lo </em>más<em> simple posible.</em></p><p>En la función Lambda, validamos el token:</p><pre>import hmac<br>import json<br>import os<br><br>def lambda_handler(event, context):<br>    # Validar el token de CloudFront<br><br>    headers = event.get(&#39;headers&#39;, {})<br>    cloudfront_expected_secret = os.environ.get(&quot;CLOUDFRONT_SECRET&quot;)<br>    cloudfront_received_secret = headers.get(&#39;x-origin-verify&#39;)<br>    <br>    if not (cloudfront_expected_secret and cloudfront_received_secret and <br>            hmac.compare_digest(cloudfront_received_secret, cloudfront_expected_secret)):<br>        return {<br>            &quot;statusCode&quot;: 403,<br>            &quot;headers&quot;: {&quot;Content-Type&quot;: &quot;application/json&quot;},<br>            &quot;body&quot;: json.dumps({<br>                &quot;error&quot;: &quot;Forbidden - Direct access not allowed&quot;,<br>                &quot;message&quot;: &quot;Access through CloudFront only&quot;<br>            })<br>        }<br>    <br>    # Tu lógica principal aquí<br>    return {<br>        &quot;statusCode&quot;: 200,<br>        &quot;body&quot;: json.dumps({&quot;message&quot;: &quot;Success!&quot;})<br>    }</pre><h4><strong>Ventajas de esta solución:</strong></h4><p><strong>1. Seguridad robusta</strong></p><ul><li>El endpoint de Lambda queda oculto del público general.</li><li>Solo requests con el token válido son procesados.</li><li>Protección contra timing attacks usando hmac.compare_digest.</li></ul><p><strong>2. Performance mejorada</strong></p><ul><li>CloudFront ofrece edge locations globales para mejor latencia.</li><li>Posibilidad de cachear responses según necesidad.</li></ul><p><strong>3. Flexibilidad operativa.</strong></p><ul><li>Fácil configuración de dominios personalizados</li><li>Certificados SSL/TLS manejados automáticamente</li><li>Posibilidad de configurar múltiples behaviors para diferentes rutas</li></ul><p><strong>4. Costo eficiente.</strong></p><ul><li>Más económico que API Gateway para casos simples</li><li>Solo pagas por requests de CloudFront e invocaciones Lambda</li><li>Sin costos fijos de infraestructura</li></ul><p><strong>5. Integración con AWS WAF.</strong></p><p>Una de las mayores ventajas de esta solución es la capacidad de integrar <strong>AWS WAF (Web Application Firewall)</strong> con CloudFront.</p><p>AWS WAF <strong>no</strong> se puede integrar directamente con Lambda Function URLs, pero sí con CloudFront. Esto te permite:</p><ul><li>Protección contra ataques DDoS automática.</li><li>Filtrado por geolocalización: Bloquear países específicos.</li><li>Rate limiting inteligente: Prevenir ataques de fuerza bruta.</li><li>Filtrado de IPs.</li><li>Protección contra OWASP Top 10: SQL injection, XSS, etc.</li><li>Reglas personalizadas: Basadas en headers, query strings, body, y más.</li></ul><h4><strong>Desafíos y consideraciones:</strong></h4><p>Esta solución requiere una configuración inicial más compleja, aunque el resultado final sea simple. Ademas el token secreto debe ser manejado de forma segura.</p><p>Por otro lado, los logs están distribuidos entre CloudFront y Lambda, lo que puede complicar el debugging inicial.</p><p>Por ultimo es bueno comentar que los cambios en CloudFront pueden tomar varios minutos en propagarse globalmente y quizas en tu solución, esto sea un problema.</p><h4><strong>Esta solución es perfecta cuando:</strong></h4><ul><li>Necesitas un endpoint HTTP simple sin la complejidad de API Gateway.</li><li>Quieres mejor performance global con edge locations.</li><li>Requieres protección básica sin autenticación IAM compleja.</li><li>Tienes una función Lambda que necesita ser accesible desde múltiples fuentes.</li><li>Buscas una solución costo-eficiente para APIs de bajo a medio volumen.</li></ul><h4><strong>Conclusión:</strong></h4><p>La combinación de CloudFront y Lambda Function URLs ofrece simplicidad, performance y seguridad. Mientras que API Gateway sigue siendo la mejor opción para APIs complejas, esta alternativa puede ser una buena opción en escenarios donde necesitas algo más que un endpoint completamente público, pero menos que una solución enterprise completa.</p><p>En mi experiencia implementando esta solución para un sistema de sincronización de datos, la combinación ha demostrado ser robusta y eficiente. La integración con AWS WAF ha sido especialmente valiosa para proteger la API de ataques automatizados.</p><p>La próxima vez que te encuentres configurando API Gateway para un simple endpoint, considera esta alternativa.</p><p>Sugerencias o comentarios de mejora, siempre son bienvenidos! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee9a5110f84f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing costs in a world that only rewards high availability]]></title>
            <link>https://medium.com/@micaelamarrero/optimizing-costs-in-a-world-that-only-rewards-high-availability-968f99c6b671?source=rss-16ebc2ca22f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/968f99c6b671</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[cloud-challenge]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Micaela Marrero]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 18:08:10 GMT</pubDate>
            <atom:updated>2025-01-26T18:22:43.909Z</atom:updated>
            <content:encoded><![CDATA[<p>The costly pursuit of perfection in the tech world, we are conditioned to chase high availability, best practices, and resilience. The allure of achieving “five nines” uptime and bulletproof infrastructure often overshadows the reality — these achievements come with a hefty price tag.</p><p>But what happens when budgets are limited, as they often are in startups or early-stage projects? How do we balance the ideals of technology with the financial constraints of reality? This article explores the delicate trade-off between cost and technology and what to prioritize in the early stages of a project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZGqWUtliQXaocTBBAn0Nw.jpeg" /></figure><p><strong>Why is high availability expensive?</strong></p><p>To understand the cost of high availability, we need to unpack what it entails. In cloud environments, achieving high availability typically means:</p><p>Multi-zone setups: Deploying resources across multiple availability zones to ensure redundancy.</p><p>Load balancing: Distributing traffic across multiple instances or servers to avoid a single point of failure.</p><p>Database replication: Keeping data synchronized across regions or nodes to prevent data loss.</p><p>Frequent backups and snapshots: Ensuring that even in the event of catastrophic failure, data can be restored quickly.</p><p>Each of these components adds incremental costs. For example, running a database with automatic failover and cross-region replication can cost 2–3x more than a single-node setup. Add to this the operational complexity of maintaining such infrastructure, and the total expense can escalate quickly.</p><p><strong>Strategies for Balancing Cost and Technology</strong></p><p>Balancing cost and availability requires careful planning and prioritization. Here are some strategies to help:</p><p>Monitor Before You Scale: invest in monitoring tools like CloudWatch or Prometheus to identify which parts of your system experience bottlenecks. Scaling unnecessarily adds costs without addressing actual needs.</p><p>Progressive scaling: instead of starting with a multi-region, multi-zone setup, grow your infrastructure alongside your user base. For example, launch in a single availability zone and expand as traffic increases.</p><p>Leverage cost-effective solutions: Opt for simpler services where possible. For instance, instead of EventBridge, a basic cron job might suffice in the beginning. Similarly, serverless options like AWS Lambda can reduce costs by only charging for execution time.</p><p>Embrace Failure with Grace: high availability doesn’t mean preventing failures entirely; it means recovering quickly. Implement automated failover mechanisms and disaster recovery plans that match your current scale.</p><p>In my current project, we faced this exact challenge, as many new companies in the tech sector do: balancing costs against high availability.</p><p>Our infrastructure runs on AWS, where we process tasks using ECS tasks running Celery. When new tasks arrive, our microservice sends them to Redis, which pushes them into a queue for Celery workers to process.</p><p>What’s the problem? In an ideal world, we’d have 50–100 ECS tasks with Celery running 24/7 to process tasks instantly. However, this would incur a <strong>huge cost</strong>! Instead, we opted for a <strong>Lambda function</strong> that checks the Redis queue every 10 seconds. When new tasks arrive, the Lambda function scales up Celery workers (ECS tasks) dynamically.</p><p>What’s the challenge? While this approach has significantly reduced costs, there’s still a <strong>1.5-minute delay</strong> to spin up a new ECS task, install dependencies, and begin processing. We continue to tackle this trade-off between cost and availability, exploring alternatives like predictive scaling or maintaining a small number of pre-warmed tasks for lighter workloads.</p><p><strong>Conclusion: resilience isn’t just about infrastructure</strong></p><p>In the early stages of a project, resilience often lies in the team’s ability to adapt, iterate, and learn quickly rather than in expensive infrastructure. As your project grows, your priorities will shift. What starts as a single EC2 instance may evolve into a multi-region, auto-scaling architecture — but only when the business demands justify it.</p><p>In the meantime, focus on what truly matters: delivering value to your users. After all, even the most resilient system is useless without a product worth using.</p><p>Sometimes, resilience isn’t about never failing; it’s about how quickly you get back up.</p><p>In my career in IT, learning to prioritize costs has been one of my greatest challenges. As engineers, we’re often drawn to the allure of perfection — building the most scalable, redundant, and fail-proof systems. But I’ve learned that a pragmatic approach, one that balances technical ideals with business realities, often leads to better outcomes. It’s not just about the technology you build; it’s about ensuring the business can sustain and grow alongside it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=968f99c6b671" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restoring stability after a Spot Instance Warning]]></title>
            <link>https://medium.com/@micaelamarrero/restoring-stability-after-a-spot-instance-warning-8ecafe674e7c?source=rss-16ebc2ca22f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ecafe674e7c</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[spot-instances]]></category>
            <category><![CDATA[dynamodb]]></category>
            <category><![CDATA[aws-cost-optimization]]></category>
            <dc:creator><![CDATA[Micaela Marrero]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 21:00:56 GMT</pubDate>
            <atom:updated>2024-10-30T07:13:39.900Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@micaelamarrero/optimizing-cloud-costs-effective-use-of-amazon-ec2-spot-instances-06bedd0796f9">first article</a>, we discussed spot instances, their benefits, and their biggest challenge: instability.</p><p>In the <a href="https://medium.com/@micaelamarrero/mitigating-downtime-with-aws-ec2-spot-instances-a-practical-approach-fea2569b6060">second article</a>, we explored a solution to this issue using a Lambda function that activates when AWS EventBridge sends a warning about our spot instances being taken.</p><p>After modifying our Auto Scaling group to use 100% on-demand instances, it’s crucial to implement a robust solution that allows our application to return to its optimal state once the warning period has ended. In this article, I will outline the steps to reintegrate Spot instances back into our architecture following a warning, restoring the balance between cost-effectiveness and application performance.</p><p>I understand there may be more optimal solutions out there; this one was born from my own imagination. So if you’re reading this and have new ideas for improvement, please don’t hesitate to share!</p><p>Let’s go to work! 🚀</p><p><strong>Testing the Implemented Solution</strong></p><p>Before we begin, the first step is to test the solution we implemented in the previous article. To do this, we will navigate to the AWS Management Console and open AWS EventBridge.</p><p>Locate the Rule: In the EventBridge dashboard, find the rule we created earlier.</p><p>Edit the Event Pattern: Click on the rule and select the “Event Pattern” tab. Here, we will edit the existing pattern to include the option “custom.testing.” This addition will enable us to trigger a test event from our terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3CqEKJ8D0yOIwT56sBbW3A.png" /></figure><p>Once we’ve made the necessary modifications, we will proceed to our terminal and execute the following command:</p><pre>aws events put-events --entries &#39;[{<br>  &quot;Source&quot;: &quot;custom.testing&quot;,<br>  &quot;DetailType&quot;: &quot;EC2 Spot Instance Interruption Warning&quot;,<br>  &quot;Detail&quot;: &quot;{\&quot;instance-id\&quot;: \&quot;i-OUR_ID\&quot;, \&quot;instance-action\&quot;: \&quot;terminate\&quot;}&quot;,<br>  &quot;Resources&quot;: [&quot;arn:aws:ec2:eu-north-1:instance/i-OUR_ID&quot;]<br>}]&#39; --region YOUR_REGION</pre><p>It is crucial to replace <strong>i-OUR_ID</strong> with the actual ID of your Spot instance. This ensures that the command accurately reflects the instance for which you want to simulate the warning. Additionally, make sure to replace <strong>YOUR_REGION</strong> with the AWS region where your resources are located.</p><p>If everything goes well, you should see the EventId in the output, indicating that our test was executed successfully.</p><pre>&quot;Entries&quot;: [<br>    {<br>        &quot;EventId&quot;: &quot;6618d5eb-afd4-7e1a-985c-4da23869d3b9&quot;<br>    }<br>]</pre><p>Is important to check AWS CloudWatch to be ensure that there were no errors during the execution of the Lambda function. Similarly, checking the Auto Scaling group settings will confirm that the desired state is now correctly reflecting the full transition to on-demand instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d2tqma3iFZPb_hysZP1-Jg.png" /></figure><p>In my case, I also subscribed to the SNS topic that receives the alert via email. This way, whenever a new alert is triggered in SNS, I receive an email notification.</p><p>This setup ensures that I’mm promptly informed about any spot instance interruptions or warnings, allowing for quick action if necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCPFCZWFhXz4nOFF29dqVQ.png" /></figure><p>Finally, we need to verify that the record in the DynamoDB table has been created successfully. To do this, navigate to the DynamoDB console and select “Explore items.” Select our table, and we should see a new record with the following data:</p><ul><li><strong>InstanceId</strong>: i-0cffffffffffff3910b0bef</li><li><strong>LastWarningReceived</strong>: 2024-10-29T20:07:24.041904</li></ul><p>This timestamp corresponds to the moment when we executed our test.</p><p>Once the tests are complete and everything is functioning correctly, we need to return to our ideal percentages of on-demand and spot instances in our Auto Scaling group.</p><p>To achieve this, we will create a Lambda function that checks whether 10 minutes have passed since the current time compared to the time recorded in the <strong>LastWarningReceived</strong> item in DynamoDB.</p><p>This function will serve as a mechanism to gradually restore the balance between on-demand and spot instances, ensuring that our architecture operates efficiently and cost-effectively after handling a spot interruption warning.</p><p>This Lambda function will execute every 5 minutes to check for any changes. If 10 minutes have passed since the current time compared to the LastWarningReceived timestamp, our Lambda function will adjust the Auto Scaling group to restore the configuration to 80% spot instances and 20% on-demand instances.</p><p>By implementing this periodic check, we ensure that our architecture can efficiently transition back to a more cost-effective setup after handling the interruption warning, maintaining a balance between performance and cost.</p><pre>import boto3<br>import os<br>from datetime import datetime, timedelta<br><br>asg_client = boto3.client(&#39;autoscaling&#39;)<br>dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>table = dynamodb.Table(os.environ[&#39;DYNAMODB_TABLE&#39;])<br><br>def lambda_handler(event, context):<br>    response = table.get_item(Key={&#39;Id&#39;: &#39;spot_instance_warning&#39;})<br>    <br>    if &#39;Item&#39; in response:<br>        last_warning = response[&#39;Item&#39;][&#39;LastWarningReceived&#39;]<br>        last_warning_time = datetime.fromisoformat(last_warning)<br>        <br>        if datetime.now() - last_warning_time &gt; timedelta(minutes=10):<br>            asg_name = os.environ[&#39;ASG_NAME&#39;]<br>            update_spot_instance_percentage(asg_name, 80)<br>            update_on_demand_percentage(asg_name, 20)<br><br>def update_spot_instance_percentage(asg_name, percentage):<br>    asg_client.update_auto_scaling_group(<br>        AutoScalingGroupName=asg_name,<br>        MixedInstancesPolicy={<br>            &#39;InstancesDistribution&#39;: {<br>                &#39;OnDemandPercentageAboveBaseCapacity&#39;: percentage<br>            }<br>        }<br>    )<br>    print(f&quot;Updated ASG {asg_name} Spot instance percentage to {percentage}%&quot;)<br><br>def update_on_demand_percentage(asg_name, percentage):<br>    asg_client.update_auto_scaling_group(<br>        AutoScalingGroupName=asg_name,<br>        MixedInstancesPolicy={<br>            &#39;InstancesDistribution&#39;: {<br>                &#39;OnDemandPercentageAboveBaseCapacity&#39;: percentage<br>            }<br>        }<br>    )<br>    print(f&quot;Updated ASG {asg_name} On-Demand instance percentage to {percentage}%&quot;)</pre><p>Note: It is important to pass the values of <strong>DYNAMODB_TABLE</strong> and <strong>ASG_NAME</strong> as environment variables in our Lambda function. This allows for greater flexibility and easier configuration management.</p><p>Additionally, we must ensure that the IAM role associated with our Lambda function has the necessary permissions to interact with both DynamoDB and the Auto Scaling group.</p><p>Finally, to ensure our Lambda function executes every 5 minutes, we need to navigate to AWS EventBridge in the console, go to Schedules, and click on Create schedule.</p><ul><li>Define Name and Description: We should provide a meaningful name and description for the schedule.</li><li>Schedule Pattern: In the Schedule pattern section, select Recurring schedule. Then, under Schedule type, choose Rate-based schedule.</li><li>Configure Execution Interval: Here, we will configure the schedule to run every 5 minutes.</li><li>Target Details: In the next tab, we will select the Target details. Choose Lambda and search for the function we created earlier.</li></ul><p>By following these steps, we can set up a schedule that ensures our Lambda function runs regularly, allowing us to monitor and adjust our Auto Scaling group as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXg8WRsTDyisob5HrGqMoA.png" /></figure><p>I hope you find this article helpful!</p><p>Feel free to share any questions or suggestions for improvement. Your feedback is always welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ecafe674e7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mitigating downtime with AWS EC2 Spot Instances: A practical approach]]></title>
            <link>https://awstip.com/mitigating-downtime-with-aws-ec2-spot-instances-a-practical-approach-fea2569b6060?source=rss-16ebc2ca22f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/fea2569b6060</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[aws-cost-optimization]]></category>
            <category><![CDATA[spot-instances]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Micaela Marrero]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 11:34:34 GMT</pubDate>
            <atom:updated>2024-10-30T14:04:35.443Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous <a href="https://medium.com/@Micaaacjs/optimizing-cloud-costs-effective-use-of-amazon-ec2-spot-instances-06bedd0796f9">article</a>, we discussed the incredible advantages of using AWS EC2 Spot instances, as well as the significant challenges posed by their instability. We already know what Spot instances are, what they are for, and how to add them to our cluster.</p><p>While Spot instances can provide substantial cost savings, they come with inherent risks due to their interruptible nature. AWS can terminate these instances when the demand for capacity rises or if the spot price exceeds your bid. This unpredictability can lead to downtime, especially for critical applications that rely on continuous uptime.</p><p>Now let’s get to work! 🚀</p><h4>Setting Up a Robust Monitoring System</h4><p>To mitigate downtime, we need to establish a robust monitoring system for EC2 Spot Instance Interruption Warnings. This involves creating an event that triggers alerts when a Spot instance is about to be interrupted. The flow for this process is:</p><ol><li><strong>Monitoring EC2 Spot Instance Interruption Warnings</strong><br>Use <strong>Amazon EventBridge</strong> to create a rule that captures EC2 Spot Instance Interruption Warnings in real time and routes them to SNS targets.</li><li><strong>Sending Alerts to AWS SNS</strong><br>When an interruption warning event occurs, EventBridge will publish a message to an Amazon Simple Notification Service (SNS) topic. This SNS topic serves as a central point for notifications related to Spot instance interruptions.</li><li><strong>Setting Up an AWS Lambda Function</strong><br>Set up an AWS Lambda function that subscribes to the SNS topic. This Lambda function will automatically execute whenever a message is published to the topic.</li></ol><p>The Lambda function will perform the following tasks when it receives an interruption warning alert:</p><p>3.1 <strong>Recording the Event in DynamoDB</strong><br>The Lambda function will log the time of the interruption in an Amazon DynamoDB table (We will discuss this in the next article)</p><p>3.2 <strong>Modifying the Auto Scaling Group</strong><br>The Lambda function will modify the associated Auto Scaling Group (ASG) configuration. Specifically, it will change the percentage of On-Demand instances in the ASG from the previous setting (20%) to 100%. This adjustment ensures that your application maintains its capacity even when Spot instances are interrupted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8TbBiQn-B32ndMMdY-V4w.png" /></figure><p>Now, let’s go step by step.</p><h3><strong>Amazon EventBridge : Creating a rule</strong></h3><p>To create the rule in Amazon EventBridge, follow these steps:</p><ol><li>Access the AWS Console: Navigate to Amazon EventBridge from the AWS Management Console.</li></ol><p>2. Create a Rule: Select “Rules” and then click on “Create rule.”</p><p>3. Configure the Rule:</p><p>In the first section:</p><ul><li>add a name and description for your rule.</li><li>Choose the rule type: “Rule with an event pattern.”</li></ul><p>In the next tab, select the option:</p><p>Event source: “AWS events or EventBridge partner events”.</p><p>To capture Spot instance interruption warnings, we need to define an event pattern that specifies which events we are interested in monitoring. In this case, our pattern will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQEeJkS8YqF0j7Cxlj533w.png" /></figure><p>4. Select the Target.</p><p>After defining the event pattern, we need to select our <strong>target</strong>, which is the resource that will receive the notification sent by Amazon EventBridge. For our example, it will be <strong>AWS SNS</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYSC4PW-fytx85ytoOFLAw.png" /></figure><p>Since we haven’t created our SNS topic yet, let’s do that next.</p><h3><strong>2. Amazon SNS : </strong>Creating a <strong>topic</strong></h3><ol><li>Navigate to Amazon SNS from the AWS Management Console.</li><li>Create a Topic:</li></ol><ul><li>Select <strong>“Topics”</strong> and then click on <strong>“Create topic.”</strong></li><li>Choose the <strong>type</strong> as <strong>Standard</strong> for our SNS topic.</li><li>Enter a <strong>name</strong> for your SNS topic and proceed to create it.</li></ul><p>3. Linking to Amazon EventBridge:</p><p>At this point, return to <strong>Amazon EventBridge</strong>. In the <strong>Target</strong> option, select the SNS topic you just created.</p><h3>3. AWS Lambda: Creating a function</h3><pre>from __future__ import print_function<br>import boto3<br>import json<br>import logging<br>from datetime import datetime<br>import os<br><br>dynamodb = boto3.resource(&#39;dynamodb&#39;)<br>client_ASG = boto3.client(&#39;autoscaling&#39;)<br><br>logging.basicConfig(level=logging.DEBUG)<br>logger = logging.getLogger()<br><br>table = dynamodb.Table(os.environ[&#39;DYNAMODB_TABLE&#39;])<br><br>def get_asg_name(instance_id):<br>    try:<br>        response = client_ASG.describe_auto_scaling_instances(<br>            InstanceIds=[instance_id]<br>        )<br>        if response[&#39;AutoScalingInstances&#39;]:<br>            return response[&#39;AutoScalingInstances&#39;][0][&#39;AutoScalingGroupName&#39;]<br>        return None<br>    except Exception as e:<br>        logger.error(f&quot;Error getting ASG name for instance {instance_id}: {e}&quot;)<br>        return None<br><br>def lambda_handler(event, context):<br>    try:<br>        logger.debug(&quot;Full event: %s&quot;, json.dumps(event))<br>        <br>        line = event[&#39;Records&#39;][0][&#39;Sns&#39;][&#39;Message&#39;]<br>        logger.debug(&quot;Raw SNS message: %s&quot;, line)<br>        <br>        if isinstance(line, str):<br>            message = json.loads(line)<br>        else:<br>            message = line<br>            <br>        logger.debug(&quot;Parsed message: %s&quot;, json.dumps(message))<br>        <br>        instance_id = None<br>        if &#39;detail&#39; in message and &#39;instance-id&#39; in message[&#39;detail&#39;]:<br>            instance_id = message[&#39;detail&#39;][&#39;instance-id&#39;]<br>        elif &#39;instance-id&#39; in message:<br>            instance_id = message[&#39;instance-id&#39;]<br>        <br>        if not instance_id:<br>            raise ValueError(&quot;Could not find instance-id in message&quot;)<br>            <br>        logger.info(f&quot;Received interruption for instance: {instance_id}&quot;)<br>        <br>        asg_name = get_asg_name(instance_id)<br>        if not asg_name:<br>            logger.error(&quot;No ASG found for instance&quot;)<br>            return {&#39;statusCode&#39;: 400, &#39;body&#39;: &#39;No ASG found for instance&#39;}<br>            <br>        timestamp = datetime.now().isoformat()<br>        <br>        table.put_item(<br>            Item={<br>                &#39;Id&#39;: &#39;spot_instance_warning&#39;,<br>                &#39;LastWarningReceived&#39;: timestamp,<br>                &#39;InstanceId&#39;: instance_id<br>            }<br>        )<br>        <br>        response = client_ASG.update_auto_scaling_group(<br>            AutoScalingGroupName=asg_name,<br>            MixedInstancesPolicy={<br>                &#39;InstancesDistribution&#39;: {<br>                    &#39;OnDemandPercentageAboveBaseCapacity&#39;: 100<br>                }<br>            }<br>        )<br>        <br>        return {<br>            &#39;statusCode&#39;: 200,<br>            &#39;body&#39;: f&#39;Warning processed for instance {instance_id} in ASG {asg_name}&#39;<br>        }<br>        <br>    except Exception as e:<br>        logger.error(f&quot;Error: {str(e)}&quot;)<br>        logger.error(&quot;Error full details:&quot;, exc_info=True)<br>        return {<br>            &#39;statusCode&#39;: 500,<br>            &#39;body&#39;: str(e)<br>        }</pre><p>This AWS Lambda function is triggered by Amazon SNS notifications when an EC2 Spot Instance interruption warning is received. Its primary responsibilities include:</p><p>1. Logging Interruption Events: The function extracts crucial information from the SNS message, such as the EC2 instance ID and the associated Auto Scaling Group (ASG) name. Records the current timestamp in a DynamoDB table. This timestamp serves as a historical reference for when interruptions occurred.</p><p>2. Updating the Auto Scaling Group: The function modifies the ASG configuration by setting the percentage of on-demand instances to 100%. This adjustment ensures that your application can maintain its capacity and availability, even when Spot instances are interrupted.</p><p>By automating these processes, the Lambda function helps to minimize downtime and ensure that critical applications continue to run smoothly during Spot instance interruptions, while also keeping a log of these events for future reference.</p><p>To subscribe this lambda function to the SNS, we can do it manually from the lambda diagram. Click on “Add a trigger” and select our SNS.</p><p>(If we want to do it differently, we can go to the Amazon SNS console → subscriptions → Create subscription → select the previously created topic, protocol we will select: “lamda” and finally, we will choose our function)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g57-tTqhHN_okIYFY0J-4A.png" /></figure><p><strong>DynamoDB Table Setup:</strong></p><p>To complete our setup, we need a DynamoDB table to store the timestamps of Spot Instance interruption warnings. This will allow us to log each interruption event, providing a historical reference.</p><p>Navigate to DynamoDB Console: Go to the AWS DynamoDB console and select “Create table.”</p><p>Define Table Attributes:</p><p>. Table Name: Choose a name that reflects the table’s purpose, like SpotInstanceWarnings.</p><p>. Partition Key: Set the partition key to Id (with data type String), which will serve as a unique identifier for each entry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKQpN89ru-t-ut-LMJMV5w.png" /></figure><h3>Last details:</h3><ol><li><strong>Add Environment Variable</strong></li></ol><p>After creating the DynamoDB table, we need to link it to our Lambda function using environment variables. Here’s how:</p><p>Copy the Table Name: Once the table is created, note its name (e.g., SpotInstanceWarnings).</p><p>Go to Lambda Configuration: Open the AWS Lambda console, navigate to your function, and go to the Configuration tab, and add a new enviorment variable.</p><p>Key: DYNAMODB_TABLE<br>Value: SpotInstanceWarnings (or the exact name of your DynamoDB table)</p><p><strong>2. Configuring IAM Permissions for the Lambda Function</strong></p><p>To allow your Lambda function to interact with both the Auto Scaling Group and DynamoDB, you’ll need to add specific permissions to the Lambda function’s execution role. Here’s how:</p><p>Open the IAM Console: Navigate to the IAM console in AWS, and locate the role associated with your Lambda function.</p><p><strong>Attach Necessary Policies:</strong></p><p>DynamoDB Permissions: To allow the function to write interruption logs, add permissions for dynamodb:PutItem. You can either attach the managed policy AmazonDynamoDBFullAccess</p><p>Auto Scaling Permissions: For the function to modify the Auto Scaling Group, add permissions for autoscaling:UpdateAutoScalingGroup.</p><p><strong>Conclusion</strong></p><p>This solution demonstrates a proactive approach to managing outages on EC2 Spot instances, leveraging AWS services to minimize potential downtime. By automating the detection and management of outage warnings with Amazon EventBridge, SNS and Lambda, we ensure that critical applications maintain availability even in the face of unpredictable Spot instances.</p><p>With this configuration, we benefit from cost savings on Spot instances without compromising reliability, making it an effective approach for organizations looking to balance performance and cost on AWS.</p><p>In the next article we will test the implemented solution and add a step to restore stability after the spot instance warning. <a href="https://medium.com/@micaelamarrero/restoring-stability-after-a-spot-instance-warning-8ecafe674e7c">Check here</a></p><p>Thanks for reading this far and I hope it has been helpful! 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fea2569b6060" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/mitigating-downtime-with-aws-ec2-spot-instances-a-practical-approach-fea2569b6060">Mitigating downtime with AWS EC2 Spot Instances: A practical approach</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing Cloud Costs: Effective Use of Amazon EC2 Spot Instances]]></title>
            <link>https://medium.com/@micaelamarrero/optimizing-cloud-costs-effective-use-of-amazon-ec2-spot-instances-06bedd0796f9?source=rss-16ebc2ca22f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/06bedd0796f9</guid>
            <category><![CDATA[cloud-cost-optimization]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[spot-instances]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud]]></category>
            <dc:creator><![CDATA[Micaela Marrero]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 09:56:30 GMT</pubDate>
            <atom:updated>2024-10-30T07:15:21.539Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction to Spot Instances</strong></p><p>Amazon EC2 Spot Instances are unused instances in the AWS cloud available at discounts of up to 90% compared to on-demand pricing. They are ideal for a variety of flexible, stateless, and fault-tolerant applications. By leveraging auction instances, enterprises can significantly reduce cloud costs while maintaining high performance.</p><p>However, despite significant discounts, users face the challenge of potential outages. AWS can terminate Spot instances on short notice, typically with a two-minute warning. This occurs when demand for on-demand instances (which are more expensive) increases, forcing AWS to reclaim that capacity to meet customer needs. Users must design applications with this uncertainty in mind. Understanding the dynamics of point-in-time instances can help organizations optimize their workloads effectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*E50zYJRf85voQoMTgOWYdw.png" /></figure><p><strong>Challenges of Using Spot Instances:</strong></p><p>The primary challenge when using Spot Instances is the possibility of interruptions. To mitigate the impact of these interruptions, organizations should consider the following strategies:</p><p>Design Fault-Tolerant Applications: Applications should be capable of quickly recovering from interruptions.</p><p>Utilize Multiple Instance Types: Diversifying instance types can increase the likelihood of maintaining the required capacity.</p><p>Implement Monitoring Systems: Establish alerts and metrics to manage the health and performance of instances.</p><p><strong>Implementation Strategies:</strong></p><p>In this article, we will discuss how to effectively use Spot Instances in both staging and production environments. We’ll explore strategies for maximizing their benefits while minimizing the impact of interruptions.</p><p>In our case, we are using an ECS cluster that has EC2 instances as nodes. Currently, we have a capacity provider that utilizes only on-demand instances. To reduce costs without compromising availability, we will create another capacity provider that employs a mixed approach, utilizing 80% Spot Instances and 20% on-demand instances.</p><p>Set up two ECS capacity providers:</p><p>ECS Capacity Provider: Mixed<br>ECS Capacity Provider: On-Demand</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xp1LMDv7mqpTemm5gvSesQ.png" /></figure><p>Both capacity providers are integrated into the ECS cluster.<br>Each provider has a weight of 1, ensuring balanced task distribution. The base is set to 0, meaning no reserved minimum tasks.</p><p>The following code in terraform defines an ECS Capacity Provider for On-Demand instances:</p><pre># --- ECS Capacity Provider ON DEMAND ---<br><br>resource &quot;aws_ecs_capacity_provider&quot; &quot;on_demand&quot; {<br><br>  name = &quot;ecs-ec2-capacity-on-demand&quot;<br><br>  auto_scaling_group_provider {<br>    auto_scaling_group_arn = aws_autoscaling_group.autoscaling_ecs_on_demand.arn<br><br>    managed_termination_protection = &quot;DISABLED&quot;<br><br>    managed_scaling {<br>      maximum_scaling_step_size = 10<br>      minimum_scaling_step_size = 1<br></pre><p>The following code defines an ECS Capacity Provider for mixed instances (On-Demand instances and spot instances):</p><pre><br># --- ECS Capacity Provider MIXED---<br><br>resource &quot;aws_ecs_capacity_provider&quot; &quot;mixed&quot; {<br><br>  name = &quot;ecs-ec2-capacity-mixed&quot;<br><br>  auto_scaling_group_provider {<br>    auto_scaling_group_arn = aws_autoscaling_group.autoscaling_ecs_mixed.arn<br><br>    managed_termination_protection = &quot;DISABLED&quot;<br><br>    managed_scaling {<br>      maximum_scaling_step_size = 10<br>      minimum_scaling_step_size = 1<br>      status                    = &quot;ENABLED&quot;<br>      target_capacity           = 100<br>    }<br>  }<br>}<br></pre><p>Finally, we attach both capacity providers to the ECS cluster.</p><pre>resource &quot;aws_ecs_cluster_capacity_providers&quot; &quot;main&quot; {<br>  cluster_name       = aws_ecs_cluster.ecs_cluster.name<br>  capacity_providers = [aws_ecs_capacity_provider.on_demand.name, aws_ecs_capacity_provider.mixed.name]<br>  default_capacity_provider_strategy {<br>    capacity_provider = aws_ecs_capacity_provider.main.name<br>    weight            = 1<br>    base              = 0<br>  }<br>  default_capacity_provider_strategy {<br>    capacity_provider = aws_ecs_capacity_provider.mixed.name<br>    weight            = 1<br>    base              = 0<br>  }<br>}<br></pre><p>With the capacity providers step done, we can now configure the Auto Scaling groups responsible for managing our EC2 instances.</p><p>Let’s define the auto-scaling group for on-demand instances:</p><pre>resource &quot;aws_autoscaling_group&quot; &quot;autoscaling_ecs_on_demand&quot; {<br>  name_prefix               = &quot;ecs-asg-on-demand-${terraform.workspace}&quot;<br>  vpc_zone_identifier       = local.subnet_private[*].id<br>  min_size                  = 1<br>  desired_capacity          = 2<br>  max_size                  = 10<br>  health_check_grace_period = 0<br>  health_check_type         = &quot;EC2&quot;<br>  protect_from_scale_in     = false<br><br>  launch_template {<br>    id      = aws_launch_template.ecs_ec2.id<br>    version = &quot;$Latest&quot;<br>  }<br><br>  tag {<br>    key                 = &quot;Name&quot;<br>    value               = &quot;ecs-ec2-${terraform.workspace}&quot;<br>    propagate_at_launch = true<br>  }<br><br>  tag {<br>    key                 = &quot;AmazonECSManaged&quot;<br>    value               = &quot;true&quot;<br>    propagate_at_launch = true<br>  }<br>}</pre><p>Then we are going to define our auto-scaling-group for the mixed instances. It is very important to define different types of instances.</p><p>In our case, the chosen percentage of on-demand instances is 20%, leaving 80% for spot instances.</p><pre>resource &quot;aws_autoscaling_group&quot; &quot;autoscaling_ecs_mixed&quot; {<br>  name                = &quot;ecs-asg-mixed-${terraform.workspace}&quot;<br>  min_size            = 1<br>  max_size            = 10<br>  desired_capacity    = 2<br>  vpc_zone_identifier = local.subnet_private[*].id<br><br>  mixed_instances_policy {<br>    launch_template {<br>      launch_template_specification {<br>        launch_template_id = aws_launch_template.ecs_ec2.id<br>        version            = &quot;$Latest&quot;<br><br>      }<br><br>      override {<br>        instance_type = &quot;c6i.2xlarge&quot;<br>      }<br>      override {<br>        instance_type = &quot;c5.2xlarge&quot;<br>      }<br>      override {<br>        instance_type = &quot;m5.2xlarge&quot;<br>      }<br>    }<br><br>    instances_distribution {<br>      on_demand_percentage_above_base_capacity = 20<br>      spot_allocation_strategy                 = &quot;capacity-optimized&quot;<br>    }<br>  }<br><br>  tag {<br>    key                 = &quot;Name&quot;<br>    value               = &quot;ecs-ec2-${terraform.workspace}&quot;<br>    propagate_at_launch = true<br>  }<br><br>  tag {<br>    key                 = &quot;AmazonECSManaged&quot;<br>    value               = &quot;true&quot;<br>    propagate_at_launch = true<br>  }<br>}</pre><p><strong>Conclusion</strong></p><p>By implementing a mixed capacity provider strategy with Amazon EC2 Spot Instances and on-demand instances, organizations can optimize their cloud infrastructure, significantly reducing costs while maintaining performance. But we still have a big question to solve, what happens when AWS needs those 80% of spot instances? We will solve it in the next <a href="https://medium.com/@micaelamarrero/mitigating-downtime-with-aws-ec2-spot-instances-a-practical-approach-fea2569b6060">article</a> :)</p><p>Thank you very much for reading my article, I hope to help you in your project 😀</p><p>All suggestions to improve my writing are welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06bedd0796f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neo4J configuration in EC2]]></title>
            <link>https://medium.com/@micaelamarrero/neo4j-configuration-in-ec2-b7d444945a21?source=rss-16ebc2ca22f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7d444945a21</guid>
            <category><![CDATA[graphdb]]></category>
            <category><![CDATA[neo4j]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[neo4j-graph-database]]></category>
            <dc:creator><![CDATA[Micaela Marrero]]></dc:creator>
            <pubDate>Thu, 18 Jul 2024 09:43:16 GMT</pubDate>
            <atom:updated>2024-07-18T09:53:57.684Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong></p><p>Neo4j is a graph-oriented database, designed to store and query highly connected data efficiently. It is developed in Java and based on a NoSQL database. It uses a declarative coding language called Cypher, which is similar to SQL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vT7mCklXHZZfMqPqMN2qiA.png" /><figcaption>76 / 5 000<br>image from <a href="https://neo4j.com/blog/neo4j-now-available-aws-marketplace/">https://neo4j.com/blog/neo4j-now-available-aws-marketplace/</a></figcaption></figure><p>Neo4j uses graph structures with nodes, relations and properties to represent and store data. It is optimized for interconnected data and is highly efficient in complex queries and relationship analysis.</p><p>Some advantages of using it in your project:</p><p>Intuitive data modeling: It represents data and relationships in a natural and easy-to-understand way.</p><p>Performance in complex queries: Very efficient for queries involving multiple relationships. Maintains high speed even with highly connected data.</p><p>Schema flexibility: Allows adding new types of relationships and properties easily.</p><p>Scalability: Designed to scale horizontally. Handles large volumes of connected data efficiently.</p><p><strong>Deploy neo4j on AWS:</strong></p><p>To deploy Neo4j on AWS, we have several options available: Neo4j Aura, which is a fully managed Neo4j service; Neo4j Enterprise on AWS Marketplace; and other options.</p><p>At the beginning of the project we decided to go for AWS Marketplace, but in this case they provide you with a cloudformation template to deploy different resources, such as VPC, subnet, NLB and the EC2 instances themselves.</p><p>This can be useful if you don’t have anything in your AWS account yet, or even as in our case, we customized the cloudformation template and deployed it without existing resources like VPC.</p><p>But what is the problem with this? The reality is that there is no big problem, but for those of us who are newbies like me in Neo4j this template solves many problems but it is difficult to understand how it works, or how to change options, add plugins, etc. So, I decided to move forward with the deployment of Neo4j on EC2 from zero. <strong>In our case we will install Neo4J enterprise version 5.17 (</strong>This is important as there are differences in installation between e.g. version 4 and 5)</p><ol><li>Create EC2 machine from terraform.</li></ol><pre>resource &quot;aws_instance&quot; &quot;ec2_neo4j&quot; {<br>  ami                    = &quot;ami-0d3a2960fcac852bc&quot;<br>  instance_type          = &quot;t3.medium&quot;<br>  key_name               = &quot;key-name&quot;<br>  subnet_id              = local.subnet_public[0].id<br>  vpc_security_group_ids = [aws_security_group.sg_neo4j.id]<br>  user_data              = filebase64(&quot;${path.module}/neo4j_install.sh&quot;)<br><br>  root_block_device {<br>    volume_size           = 100<br>    delete_on_termination = true<br>    volume_type           = &quot;gp3&quot;<br>  }<br><br>  tags = merge(local.tags, {<br>    Name = &quot;db-neo4j-${terraform.workspace}&quot;<br>  })<br>}</pre><p>In this case I was using a t3.medium for cost purpose, but you can use:</p><pre>t3.medium<br>t3.large<br>t3.xlarge<br>t3.2xlarge<br>r6i.large<br>r6i.xlarge<br>r6i.2xlarge<br>r6i.4xlarge<br>r6i.8xlarge<br>r6i.12xlarge<br>r6i.16xlarge<br>r6i.24xlarge<br>r6i.32xlarge</pre><p>2. Create a security group</p><pre><br>resource &quot;aws_security_group&quot; &quot;sg_neo4j&quot; {<br>  name   = &quot;neo4j-sg-${terraform.workspace}&quot;<br>  vpc_id = local.vpc_id<br><br>  ingress {<br>    description = &quot;allow SSH&quot;<br>    from_port   = 22<br>    to_port     = 22<br>    protocol    = &quot;TCP&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  ingress {<br>    description = &quot;allow 7474&quot;<br>    from_port   = 7474<br>    to_port     = 7474<br>    protocol    = &quot;TCP&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br>  ingress {<br>    description = &quot;allow 7687&quot;<br>    from_port   = 7687<br>    to_port     = 7687<br>    protocol    = &quot;TCP&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }<br><br>  tags = merge(local.tags, {<br>    Name = &quot;neo4j-sg-${terraform.workspace}&quot;<br>  })<br>}</pre><p>Our EC2 machine has in user_data a script that installs neo4j, configures all the necessary and installs some plugins that we use. In our case it is APOC, neosemantic and graph data science.</p><pre>#!/bin/bash<br>sudo yum update -y<br><br>sudo rpm --import https://debian.neo4j.com/neotechnology.gpg.key<br><br>if [[ ! -e /etc/yum.repos.d/neo4j.repo ]]; then<br>    sudo touch /etc/yum.repos.d/neo4j.repo<br>    sudo bash -c &#39;cat &lt;&lt;EOF &gt; /etc/yum.repos.d/neo4j.repo<br>[neo4j]<br>name=Neo4j RPM Repository<br>baseurl=https://yum.neo4j.com/stable/5<br>enabled=1<br>gpgcheck=1<br>EOF<br>&#39;<br>else<br>    echo &quot;The file already exists&quot;<br>fi</pre><p>At the start of the script we will download the Neo4j GPG key from the URL provided. We import this key into the RPM package management system. This key will be used to verify the authenticity of Neo4j packages installed later.</p><p>It also verifies the existence of the Neo4j repository configuration file for yum. If the file does not exist, it creates it and adds the necessary configuration for yum to use the Neo4j repository.</p><pre>replace_line() {<br>    local search=&quot;$1&quot;<br>    local replace=&quot;$2&quot;<br>    local file=&quot;/etc/neo4j/neo4j.conf&quot;<br>    if grep -q &quot;^#*$search&quot; &quot;$file&quot;; then<br>        sudo sed -i &quot;s|^#*$search.*|$replace|&quot; &quot;$file&quot;<br>    else<br>        echo &quot;$replace&quot; | sudo tee -a &quot;$file&quot; &gt; /dev/null<br>    fi<br>}<br><br>if rpm -q neo4j-enterprise &amp;&gt;/dev/null; then<br>    echo &quot;Neo4j service is installed and running&quot;<br>else<br>    echo &quot;Neo4j service isn&#39;t installed. Installing ...&quot;<br>    sudo NEO4J_ACCEPT_LICENSE_AGREEMENT=yes yum install neo4j-enterprise-5.17.0 -y<br><br>    # Replace lines in neo4j.conf<br>    replace_line &quot;#server.bolt.listen_address=:7687&quot; &quot;server.bolt.listen_address=0.0.0.0:7687&quot;<br>    replace_line &quot;#server.http.listen_address=:7474&quot; &quot;server.http.listen_address=0.0.0.0:7474&quot;<br>    replace_line &quot;#server.https.listen_address=:7473&quot; &quot;server.https.listen_address=0.0.0.0:7473&quot;<br><br>    echo &quot;Neo4j configuration has been updated.&quot;<br>    sudo systemctl start neo4j<br>fi</pre><p>All Neo4J configuration will be done in the <strong>/etc/neo4j/neo4j.conf</strong> file.</p><p>Here we see a function replace_line() to replace lines in the configuration file. Then the script checks if Neo4j Enterprise is installed. If it is not, it installs it and updates its neo4j.conf configuration file to allow connections in ports:</p><p>7687 (Bolt): neo4j clients, such as applications that connect to the database, use this port to execute queries and operations against the database.</p><p>7474(HTTP): This port is used for the Neo4j HTTP interface. Through this port, users can access the Neo4j REST API, as well as the web interface for administration and data exploration.</p><p>7473(HTTPS): This port is used for the secure version (HTTPS) of the Neo4j HTTP interface.</p><p>Finally the script starts the Neo4j service.</p><p>If we deploy this configuration, we should have Neo4j running on our system within a few minutes. <strong>By default, the user created is ‘neo4j’ with the password ‘neo4j’.</strong></p><p>If we access through our public dns and port 7474 we should be able to see the neo4j interface.</p><p><strong>Installing neo4j plugins:</strong></p><p><strong>APOC:</strong></p><p>We will continue installing the desired plugins. By default, all plugins are hosted in: <strong>/var/lib/neo4j/plugins</strong></p><p>The first one we install is APOC. Since Neo4j version 5, to install this plugin we also need to create a file in /etc/neo4j/apoc.conf</p><pre>#APOC<br>if [ -e &quot;/var/lib/neo4j/plugins/apoc-5.21.0-core.jar&quot; ]; then<br>    echo &quot;APOC plugin is already downloaded and installed&quot;<br>else<br>    sudo wget https://github.com/neo4j/apoc/releases/download/5.21.0/apoc-5.21.0-core.jar -P /var/lib/neo4j/plugins<br>    sudo chown neo4j:neo4j /var/lib/neo4j/plugins/apoc-5.21.0-core.jar<br>    sudo chmod 755 /var/lib/neo4j/plugins/apoc-5.21.0-core.jar<br><br>    if [[ ! -e /etc/neo4j/apoc.conf ]]; then<br>        sudo touch /etc/neo4j/apoc.conf<br>        sudo bash -c &#39;cat &lt;&lt;EOF &gt; /etc/neo4j/apoc.conf<br>apoc.export.file.enabled=true<br>apoc.import.file.use_neo4j_config=false<br>EOF&#39;<br>    else<br>        echo &quot;APOC configuration file already exists&quot;<br>    fi  <br>fi</pre><p>If we find the apoc-5.21.0-core.jar file, we assume that APOC is already installed in our database. Otherwise, we download the .jar file and give permissions to the neo4j user. (It is very important that the plugin version is compatible with the Neo4j version we have installed).</p><p>After that, we check if the /etc/neo4j/apoc.conf, if not, we create it with the apoc configuration.</p><p><strong>NEOMANTIC and GDS:</strong></p><p>For the rest of the plugins, the process is simpler since we must only download the .jar in the plugins folder and small configurations.</p><pre>#NEOSEMANTIC<br>if [ -e &quot;/var/lib/neo4j/plugins/neosemantics-5.17.0.jar&quot; ]; then<br>    echo &quot;neosemantics plugin is already downloaded and installed&quot;<br>else<br>    sudo wget https://github.com/neo4j-labs/neosemantics/releases/download/5.17.0/neosemantics-5.17.0.jar -P /var/lib/neo4j/plugins<br>    sudo chown neo4j:neo4j /var/lib/neo4j/plugins/neosemantics-5.17.0.jar<br>    sudo chmod 755 /var/lib/neo4j/plugins/neosemantics-5.17.0.jar<br>    replace_line &quot;dbms.unmanaged_extension_classes=&quot; &quot;dbms.unmanaged_extension_classes=n10s.endpoint=/rdf&quot;<br>fi</pre><pre>#Graph-data-science<br>if [ -e &quot;/var/lib/neo4j/plugins/neo4j-graph-data-science-2.7.0.jar&quot; ]; then<br>    echo &quot;Graph-data-science plugin is already downloaded and installed&quot;<br>else<br>    sudo wget https://github.com/neo4j/graph-data-science/releases/download/2.7.0/neo4j-graph-data-science-2.7.0.jar -P /var/lib/neo4j/plugins<br>    sudo chown neo4j:neo4j /var/lib/neo4j/plugins/neo4j-graph-data-science-2.7.0.jar<br>    sudo chmod 755 /var/lib/neo4j/plugins/neo4j-graph-data-science-2.7.0.jar<br>fi</pre><p>We must change the Neo4j configuration to allow the installed plugins.</p><p>Finally, we restart the database to apply the changes.</p><pre>sudo sh -c &#39;echo &quot;dbms.security.procedures.unrestricted=apoc.*,n10s.*,gds.*&quot; &gt;&gt; /etc/neo4j/neo4j.conf&#39;<br>sudo sh -c &#39;echo &quot;dbms.security.procedures.allowlist=apoc.*,n10s.*,gds.*&quot; &gt;&gt; /etc/neo4j/neo4j.conf&#39;<br><br># Restart Neo4j to apply all changes<br>sudo systemctl restart neo4j</pre><p>This installation allows us to have clearer and easier-to-understand control over our database. In the future, we plan to improve security and scalability, since this is a database that currently has no redundancy and cannot scale horizontally or vertically.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7d444945a21" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring ENI trunking on ECS to increase the task limit per EC2 node.]]></title>
            <link>https://medium.com/@micaelamarrero/configuring-eni-trunking-on-ecs-to-increase-the-task-limit-per-ec2-node-70b655cb7228?source=rss-16ebc2ca22f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/70b655cb7228</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ec2-instance]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[aws-ecs]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Micaela Marrero]]></dc:creator>
            <pubDate>Tue, 04 Jun 2024 08:39:48 GMT</pubDate>
            <atom:updated>2024-06-04T08:39:48.252Z</atom:updated>
            <content:encoded><![CDATA[<p>When we create an ECS cluster using EC2 nodes we have different network options available for tasks to communicate with the outside. The normally used options are: <strong>awsvpc, bridge and host.</strong></p><p>Each network option has its advantages and disadvantages that I will try to explain easily:</p><p><strong>awsvpc:</strong> In this mode each task gets its own Elastic Network Interface (ENI) with an assigned IP address. This mode offers the highest level of network isolation and security.</p><p><strong>Bridge</strong>: This mode uses the default Docker network bridge to connect containers. Containers share the same host network interface and can communicate with each other through localhost or through the Docker network bridge. It does not provide complete network isolation, as all containers share the same underlying network.</p><p><strong>Host:</strong> In this mode containers use the network of the underlying EC2 host it is running on. This means that containers do not run in their own virtual network, they share the network with the EC2 instance. This mode can improve network performance but reduces isolation and security.</p><p><em>(more info: </em><a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-networking.html"><em>https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-networking.html</em></a><em>)</em></p><p>The mode recommended by AWS is: <strong>awsvpc</strong>. This mode has many advantages, but it has a big problem when we try to execute large amounts of tasks in our ECS cluster. As we saw, each task gets its own ENI and IP address, but the number of ENIs available per EC2 instance (underlying node) is limited.</p><p>For example, if our ECS cluster uses EC2 nodes of type: <strong>c5.large</strong> we will have 3 ENIs available, where: 1 ENI will be used by EC2 itself and we will only have 2 ENIs available that will allow us to execute 2 tasks.</p><p>To solve this problem there is: <strong>ENI trunking. </strong>This powerful feature allows our EC2 instances to have a primary ENI and the trunk ENI, on which we can deploy many ECS tasks, and each will be assigned its corresponding IP address.</p><p>In the case of our EC2 nodes of type c5.large we are going from 3 ENI available to 10 ENI available with ENI trunking. It sounds great 😊</p><p><em>(Moro info: </em><a href="https://docs.aws.amazon.com/AmazonECS/latest/developerguide/eni-trunking-supported-instance-types.html"><em>https://docs.aws.amazon.com/AmazonECS/latest/developerguide/eni-trunking-supported-instance-types.html</em></a><em>)</em></p><p>Our new architecture should look like this:</p><figure><img alt="(image from: https://docs.aws.amazon.com/AmazonECS/latest/bestpracticesguide/networking-networkmode-awsvpc.html)" src="https://cdn-images-1.medium.com/max/1024/1*0oRlJD4RNvEfF9Lhgl4Mmw.png" /></figure><p>Now let’s get to work to enable ENI trunking in our ECS cluster 💪:</p><ol><li>The first thing we need to check is the <strong>ECS instance type</strong>. Only some types are supported, so we need to check if our instance type supports this feature.</li><li>ENI trunking was enabled on ECS optimized AMIs. We can search our AWS console for optimized AMIs or solve it from terraform.</li></ol><pre>data &quot;aws_ssm_parameter&quot; &quot;ecs_node_ami&quot; {<br>  name = &quot;/aws/service/ecs/optimized-ami/amazon-linux-2/recommended/image_id&quot;<br>}<br><br>resource &quot;aws_launch_template&quot; &quot;ecs_ec2&quot; {<br>  name_prefix   = &quot;lt-ecs-ec2-${terraform.workspace}&quot;<br>  image_id      = data.aws_ssm_parameter.ecs_node_ami.value<br>  instance_type = &quot;c5.large&quot; <br>  vpc_security_group_ids = [aws_security_group.ecs-security-group.id]<br>}</pre><p>3. The network mode of our tasks must be: awsvpc.</p><pre><br>resource &quot;aws_ecs_task_definition&quot; &quot;ecs-4. task-ms1&quot; {<br>  family                   = &quot;ecs-task-${var.microservicio-1}&quot;<br>  task_role_arn            = aws_iam_role.ecs_task_role.arn<br>  execution_role_arn       = aws_iam_role.ecs_exec_role.arn<br>  requires_compatibilities = [&quot;EC2&quot;]<br>  network_mode             = &quot;awsvpc&quot;<br>}</pre><p>4. Is necessary to enable ENI trunking in our VPC. We can do it from the awscli using:</p><pre>aws ecs put-account-setting-default --name awsvpcTrunking --value enabled --region your_region</pre><p>We can verify that it was enabled using the command:</p><pre>aws ecs list-account-settings --effective-settings</pre><p>5. The last consideration is to ensure that our subnets have enough IP addresses available. With this new implementation each task will use a different IP, so we will have problems with small subnets.</p><p>By following these steps we should be able to enable ENI trunking on our ECS cluster and optimize the performance of our applications 💪</p><p>I hope this article has been helpful to you :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70b655cb7228" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>