<?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 Nazmul Haque Nahin on Medium]]></title>
        <description><![CDATA[Stories by Nazmul Haque Nahin on Medium]]></description>
        <link>https://medium.com/@nahin.cdr?source=rss-a0bf9999dd08------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RVLAYj1fPe9nKKgvEgLthw.jpeg</url>
            <title>Stories by Nazmul Haque Nahin on Medium</title>
            <link>https://medium.com/@nahin.cdr?source=rss-a0bf9999dd08------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 14:26:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nahin.cdr/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[How to Detect System Dark Mode in Flutter and Sync App Theme with Device]]></title>
            <link>https://medium.com/@nahin.cdr/how-to-detect-system-dark-mode-in-flutter-and-sync-app-theme-with-device-9d81f26fafe5?source=rss-a0bf9999dd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d81f26fafe5</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[flutter-system-theme]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[nativelens]]></category>
            <category><![CDATA[dark-mode-flutter]]></category>
            <dc:creator><![CDATA[Nazmul Haque Nahin]]></dc:creator>
            <pubDate>Sun, 31 May 2026 17:05:38 GMT</pubDate>
            <atom:updated>2026-05-31T17:05:38.715Z</atom:updated>
            <content:encoded><![CDATA[<h4>NativeLens v0.10.0: Real-time light/dark theme detection for Flutter apps</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZEuvm7UPTLDoIlm-Y6ekw.png" /></figure><h4>Imagine this…</h4><p>A user opens your Flutter app at night. Their phone is already using <strong>dark mode</strong>.</p><p>But your app opens in <strong>light mode</strong>.</p><p>Bright screen. Bad experience.</p><p>Now the user goes to your app settings and selects:</p><blockquote><em>Sync with device theme</em></blockquote><p>This sounds simple.</p><p>But your app now needs to know two things:</p><ol><li>Is the device currently in light mode or dark mode?</li><li>If the user changes the system theme, can the app detect it in real time?</li></ol><p>That is exactly what <strong>NativeLens v0.10.0</strong> helps Flutter developers do.</p><h3>The Problem: Flutter Apps Need Better Theme Awareness</h3><p>Many modern mobile apps offer theme options like:</p><pre>Light<br>Dark<br>Sync with device</pre><p>Light and Dark are easy.</p><p>But <strong>Sync with device</strong> needs a native signal from the device.</p><p>For example:</p><pre>Device switches to dark mode<br>↓<br>Flutter app should update theme automatically</pre><p>This is useful for apps that want a more native and smooth user experience.</p><h3>The Solution: NativeLens Theme Mode Intelligence</h3><p><strong>NativeLens</strong> is a Flutter package that helps developers understand native device capability and state before a feature starts.</p><p>In version <strong>0.10.0</strong>, NativeLens added:</p><pre>Native Theme Mode Intelligence</pre><p>It allows Flutter apps to:</p><pre>Detect current system theme mode<br>Listen to real-time light/dark mode changes<br>Support Android and iOS<br>Use safe unknown fallback</pre><h3>Install NativeLens</h3><p>Add the package:</p><pre>dependencies:<br>  native_lens: ^0.10.0</pre><p>Import it:</p><pre>import &#39;package:native_lens/native_lens.dart&#39;;</pre><h3>Detect Current System Theme in Flutter</h3><p>To check the current native device theme:</p><pre>final themeMode = await NativeLens().getThemeMode();</pre><pre>print(themeMode);</pre><p>Possible result:</p><pre>NativeLensThemeMode.light<br>NativeLensThemeMode.dark<br>NativeLensThemeMode.unknown</pre><p>Example:</p><pre>Future&lt;void&gt; checkTheme() async {<br>  final theme = await NativeLens().getThemeMode();</pre><pre>  if (theme == NativeLensThemeMode.dark) {<br>    print(&#39;Device is using dark mode&#39;);<br>  } else if (theme == NativeLensThemeMode.light) {<br>    print(&#39;Device is using light mode&#39;);<br>  } else {<br>    print(&#39;Theme mode is unknown&#39;);<br>  }<br>}</pre><p>This is helpful when your app starts and you want to apply the correct theme immediately.</p><h3>Listen to Real-time Theme Changes</h3><p>Sometimes the user changes the system theme while your app is running.</p><p>NativeLens can listen to that change:</p><pre>late final StreamSubscription&lt;NativeLensThemeMode&gt; _themeSubscription;</pre><pre>@override<br>void initState() {<br>  super.initState();</pre><pre>  _themeSubscription = NativeLens().watchThemeMode().listen((themeMode) {<br>    print(&#39;System theme changed: $themeMode&#39;);</pre><pre>    // Update your app theme here<br>  });<br>}</pre><pre>@override<br>void dispose() {<br>  _themeSubscription.cancel();<br>  super.dispose();<br>}</pre><p>Now your Flutter app can react when the device changes from light mode to dark mode, or dark mode to light mode.</p><h3>Convert NativeLens Theme to Flutter ThemeMode</h3><p>Flutter uses ThemeMode.</p><p>NativeLens uses NativeLensThemeMode.</p><p>You can map them like this:</p><pre>ThemeMode mapNativeThemeMode(NativeLensThemeMode mode) {<br>  switch (mode) {<br>    case NativeLensThemeMode.light:<br>      return ThemeMode.light;</pre><pre>    case NativeLensThemeMode.dark:<br>      return ThemeMode.dark;</pre><pre>    case NativeLensThemeMode.unknown:<br>      return ThemeMode.system;<br>  }<br>}</pre><p>Then update your app state:</p><pre>NativeLens().watchThemeMode().listen((nativeTheme) {<br>  final flutterThemeMode = mapNativeThemeMode(nativeTheme);</pre><pre>  // Update Provider, Riverpod, Bloc, Cubit, or setState<br>});</pre><h3>Real Use Case: “Sync with Device” Theme Setting</h3><p>Suppose your app has this setting:</p><pre>App Theme<br>- Light<br>- Dark<br>- Sync with device</pre><p>When the user selects <strong>Sync with device</strong>, you can use NativeLens:</p><pre>final nativeLens = NativeLens();</pre><pre>final currentTheme = await nativeLens.getThemeMode();</pre><pre>final currentFlutterTheme = mapNativeThemeMode(currentTheme);</pre><pre>// Apply currentFlutterTheme to your app</pre><p>Then listen for future changes:</p><pre>nativeLens.watchThemeMode().listen((themeMode) {<br>  final updatedTheme = mapNativeThemeMode(themeMode);</pre><pre>  // Apply updatedTheme to your app<br>});</pre><p>This makes your Flutter app feel more connected to the device.</p><h3>Why This Matters</h3><p>Theme is not just a UI feature.</p><p>It affects comfort, readability, battery experience, and how natural your app feels.</p><p>A user expects:</p><pre>Phone is dark<br>App should be dark</pre><p>With NativeLens, Flutter developers can detect the native system theme and react to changes in real time.</p><p>No heavy polling.<br>No complex setup.<br>Just a clean native signal.</p><h3>Final Thought</h3><p>NativeLens is moving toward one bigger goal:</p><blockquote><em>Understand the device before the feature starts.</em></blockquote><p>Theme mode detection is a small but practical part of that vision.</p><p>With <strong>NativeLens v0.10.0</strong>, Flutter apps can now detect system light/dark mode and support real-time “Sync with device theme” behavior.</p><p>Package:<br><a href="https://pub.dev/packages/native_lens">https://pub.dev/packages/native_lens</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d81f26fafe5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NativeLens: A Flutter Package for Device Capability Intelligence Before Your Feature Fails]]></title>
            <link>https://medium.com/@nahin.cdr/nativelens-a-flutter-package-for-device-capability-intelligence-before-your-feature-fails-8d7a2c086c91?source=rss-a0bf9999dd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d7a2c086c91</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Nazmul Haque Nahin]]></dc:creator>
            <pubDate>Wed, 27 May 2026 04:42:04 GMT</pubDate>
            <atom:updated>2026-05-27T04:42:04.124Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical Flutter plugin that helps apps inspect device capabilities, understand runtime risks, and make safer product decisions on real Android and iOS devices.</h4><h3>Why I Built NativeLens</h3><p>When building production Flutter apps, many problems do not come from the UI layer. They come from the real device.</p><p>A feature may look simple in development, but fail on a user’s phone because:</p><ul><li>the device does not have the required sensor,</li><li>the camera capability is limited,</li><li>the network is connected but not actually reliable,</li><li>the battery is too low,</li><li>power saver mode is enabled,</li><li>the device does not support the required media codec,</li><li>or the phone is simply not ready for that specific task.</li></ul><p>Most apps discover these problems too late: after a crash, failed upload, broken recording, bad user experience, or support complaint.</p><p>That is why I built <strong>NativeLens</strong>.</p><p>NativeLens is a Flutter package designed to help developers inspect device capabilities and make safer decisions before starting risky features.</p><p>The core idea is simple:</p><blockquote><em>Do not wait for a feature to fail. Check whether the device is ready first.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dIWOXLEU4YF5FVrVE5scA.png" /><figcaption>Flutter device capability package, Flutter device diagnostics, Flutter native plugin, Flutter camera capability check, Flutter sensor detection, Flutter network capability, Flutter battery state, Flutter compatibility report, Flutter task risk analysis, Flutter native splash setup, Flutter production app reliability, Flutter Android device profiling, Flutter iOS safe fallback, mobile app device readiness, Flutter feature preflight check</figcaption></figure><h3>What NativeLens Is</h3><p>NativeLens is a Flutter native capability intelligence package.</p><p>It helps Flutter developers collect useful device signals such as platform information, sensors, camera capabilities, display details, battery state, network capability, media codecs, orientation, and compatibility information.</p><p>But the bigger goal is not only to show raw data.</p><p>NativeLens is built to help answer product-level questions like:</p><ul><li>Is this device ready for video recording?</li><li>Is this device suitable for a live streaming feature?</li><li>Is this phone missing an important sensor?</li><li>Should I show a fallback experience?</li><li>Should I warn the user before starting a heavy task?</li><li>Can this device safely continue with this feature?</li></ul><p>That makes NativeLens useful for production Flutter apps where device readiness matters.</p><h3>Install NativeLens</h3><pre>dependencies:<br>  native_lens: ^0.7.0</pre><p>Then import it:</p><pre>import &#39;package:native_lens/native_lens.dart&#39;;</pre><h3>1. Platform and Device Diagnostics</h3><p>NativeLens can collect platform and device-level summary information.</p><p>This is useful when you want to understand what kind of device your app is running on, especially during debugging, QA testing, support investigation, or compatibility checks.</p><p>Example use cases:</p><ul><li>device diagnostics screen,</li><li>internal QA tool,</li><li>support report,</li><li>low-end device detection,</li><li>compatibility investigation.</li></ul><pre>final summary = await NativeLens().getPlatformSummary();</pre><p>This gives developers a clean starting point for understanding the runtime environment.</p><h3>2. System Feature Detection</h3><p>NativeLens can inspect system-level features exposed by the device.</p><p>This is useful for checking whether the device supports capabilities such as camera, microphone, Bluetooth, location-related features, sensors, and other Android system features.</p><pre>final features = await NativeLens().getSystemFeatures();</pre><p>Why this matters:</p><p>A feature should not be enabled only because your app UI has a button. It should be enabled because the device can actually support it.</p><h3>3. Sensor Detection</h3><p>Many modern app features depend on sensors.</p><p>Examples:</p><ul><li>fitness tracking,</li><li>step counter,</li><li>compass navigation,</li><li>AR experience,</li><li>face filter effects,</li><li>motion-based UI,</li><li>device orientation behavior.</li></ul><p>NativeLens can list available device sensors.</p><pre>final sensors = await NativeLens().getSensors();</pre><p>This helps developers understand whether the device has sensors such as accelerometer, gyroscope, magnetometer, step counter, and other hardware sensors.</p><p>Instead of assuming every device has the same sensor set, NativeLens helps you check reality.</p><h3>4. Display Information, Refresh Rate, and HDR Support</h3><p>Display capability affects user experience, animation quality, gaming, media playback, and visual-heavy interfaces.</p><p>NativeLens can provide display information such as refresh rate and HDR-related capability.</p><pre>final display = await NativeLens().getDisplayInfo();</pre><p>This is useful when your app needs to adapt visual quality based on the device.</p><p>For example:</p><ul><li>lower animation intensity on weaker displays,</li><li>detect high refresh rate devices,</li><li>understand HDR support,</li><li>tune media or visual experience.</li></ul><h3>5. Camera Capability Profiling</h3><p>Camera-based features are sensitive.</p><p>A camera feature can fail or behave poorly if the device camera hardware level, autofocus support, stabilization support, or FPS range is limited.</p><p>NativeLens can inspect camera capabilities without opening the camera or capturing media.</p><pre>final cameras = await NativeLens().getCameraCapabilities();</pre><p>Useful for:</p><ul><li>camera apps,</li><li>video recording apps,</li><li>QR scanner apps,</li><li>AR or face filter apps,</li><li>document scanner apps,</li><li>production camera compatibility checks.</li><li>NativeLens helps developers make smarter decisions before starting the camera feature.</li></ul><h3>6. Media Codec Capability</h3><p>Media-heavy apps often depend on codec support.</p><p>Examples:</p><ul><li>video recording,</li><li>video editing,</li><li>video upload compression,</li><li>live streaming,</li><li>audio processing,</li><li>playback optimization.</li></ul><p>NativeLens can inspect available media codecs.</p><pre>final codecs = await NativeLens().getMediaCodecs();</pre><p>This helps developers understand whether a device supports important video or audio codecs and whether a fallback should be used.</p><p>For production apps, this can reduce unexpected media failures on real devices.</p><h3>7. Battery and Power State</h3><p>A feature may technically work, but still be risky when the battery is too low or power saver mode is enabled.</p><p>NativeLens can provide battery and power state information.</p><pre>final power = await NativeLens().getPowerState();</pre><p>NativeLens also supports live power state updates:</p><pre>final subscription = NativeLens().watchPowerState().listen((power) {<br>  // React to battery or power saver changes.<br>});</pre><p>Useful for:</p><ul><li>video upload,</li><li>background sync,</li><li>long recording sessions,</li><li>live streaming,</li><li>heavy processing,</li><li>warning users before starting battery-sensitive tasks.</li></ul><h3>8. Network Capability and Live Network Updates</h3><p>Network status is not only about Wi-Fi or mobile data.</p><p>A device may appear connected, but the internet may not be validated or stable enough for a critical task.</p><p>NativeLens can inspect network capability and provide live updates.</p><pre>final network = await NativeLens().getNetworkCapability();</pre><p>Live network capability stream:</p><pre>final subscription = NativeLens().watchNetworkCapability().listen((network) {<br>  // React to network capability changes.<br>});</pre><p>NativeLens can also provide network speed-related updates where supported.</p><p>This is useful for:</p><ul><li>uploads,</li><li>downloads,</li><li>video calls,</li><li>live streaming,</li><li>background sync,</li><li>offline-first apps,</li><li>network-aware feature gating.</li></ul><h3>9. Orientation Snapshot and Live Orientation Stream</h3><p>Some features depend heavily on orientation.</p><p>NativeLens can provide orientation information and live orientation updates.</p><pre>final orientation = await NativeLens().getOrientation();</pre><pre>final subscription = NativeLens().watchOrientation().listen((orientation) {<br>  // React to orientation changes.<br>});</pre><p>Useful for camera apps, media apps, AR experiences, game-like interfaces, and responsive UI behavior.</p><h3>10. Compatibility Report</h3><p>NativeLens can generate a compatibility-style report from device signals.</p><p>This helps developers get a higher-level view of how ready or capable the current device is.</p><pre>final report = await NativeLens().generateReport();</pre><p>A report can be useful for:</p><ul><li>support diagnostics,</li><li>QA device comparison,</li><li>production troubleshooting,</li><li>internal testing tools,</li><li>device readiness dashboards.</li></ul><h3>11. Task Risk Analysis</h3><p>This is where NativeLens becomes more than a raw device information package.</p><p>NativeLens can analyze predefined task types and return a risk result.</p><p>Example tasks may include things like video upload, media processing, camera capture, audio recording, background sync, real-time streaming, AR experience, step tracking, or compass navigation.</p><pre>final result = await NativeLens().analyzeTaskRisk(NativeLensTask.videoUpload);</pre><p>A task risk result can help answer:</p><ul><li>Is this task low, medium, or high risk?</li><li>What warnings should the developer know?</li><li>What recommendations should the app follow?</li><li>Should the app continue or show a fallback?</li></ul><p>This is especially useful for production mobile apps where user devices vary widely.</p><h3>12. Capability Requirement Engine</h3><p>NativeLens can also help compare required capabilities against available capabilities.</p><p>This is useful when a feature needs specific hardware or runtime conditions.</p><p>Instead of manually checking many separate signals, NativeLens can help organize the result into available and missing capabilities.</p><p>This makes it easier to build feature gating, fallback logic, and user-friendly warnings.</p><h3>13. Dataset Export for Device Intelligence Workflows</h3><p>NativeLens can generate device capability dataset rows and export data in JSON or CSV format.</p><p>This is useful for developers who want to collect structured device-readiness information for testing, analysis, QA, or future intelligence workflows.</p><pre>final row = await NativeLens().generateDatasetRow();</pre><p>Export options:</p><pre>final json = await NativeLens().exportDatasetJson();<br>final csv = await NativeLens().exportDatasetCsv();</pre><p>This can help teams build a better understanding of the device landscape their apps run on.</p><h3>14. Native Splash Setup Tool</h3><p>NativeLens also includes a native splash setup tool.</p><p>Flutter developers often need native-level splash screen setup for Android and iOS. NativeLens provides a command-based setup flow.</p><p>Example configuration:</p><pre>native_lens:<br>  splash:<br>    background_color: &quot;#0B1020&quot;<br>    image: assets/splash/logo.png<br>    android: true<br>    ios: true</pre><p>Run:</p><pre>dart run native_lens:splash</pre><p>This is useful for setting up native splash assets and platform files in a structured way.</p><h3>15. Custom Task Requirements</h3><p>NativeLens is also evolving toward custom task/device readiness analysis.</p><p>With custom task requirements, a developer can define what a feature needs, and NativeLens can return a readiness-style result.</p><p>Example:</p><pre>final result = await NativeLens().analyzeCustomTask(<br>  taskName: &#39;Face Filter Camera&#39;,<br>  requirements: const NativeLensTaskRequirements(<br>    requiresCamera: true,<br>    requiresMicrophone: false,<br>    requiresStableNetwork: true,<br>    requiredSensors: [&#39;gyroscope&#39;, &#39;accelerometer&#39;],<br>    minBatteryLevel: 20,<br>  ),<br>);</pre><p>The result can include:</p><pre>print(result.riskLevel);<br>print(result.severity);<br>print(result.canContinue);<br>print(result.missingCapabilities);<br>print(result.recommendations);<br>print(result.userMessage);<br>print(result.developerMessage);</pre><p>This allows Flutter apps to perform a feature preflight check before starting a risky flow.</p><p>For example, before enabling a face filter camera feature, an app can check whether the device has the required camera, sensors, battery level, and network condition.</p><p>If the device is not ready, the app can show a safer fallback instead of letting the feature fail.</p><h3>Why Developers Might Use NativeLens</h3><p>NativeLens is useful because it focuses on production device readiness.</p><p>Many packages provide raw signals. NativeLens tries to help developers turn those signals into decisions.</p><p>Instead of only asking:</p><blockquote><em>What does this device have?</em></blockquote><p>NativeLens helps ask:</p><blockquote><em>Is this device ready for this feature?</em></blockquote><p>That difference matters in real apps.</p><p>A production app does not only need information. It needs decisions, fallbacks, warnings, and safer behavior.</p><h3>Strong Use Cases</h3><p>NativeLens can be useful for:</p><ul><li>Flutter camera apps,</li><li>video recording apps,</li><li>live streaming apps,</li><li>AR and face filter apps,</li><li>fitness and sensor-based apps,</li><li>offline-first apps,</li><li>upload/download-heavy apps,</li><li>QA and device testing tools,</li><li>production support diagnostics,</li><li>low-end Android compatibility checks,</li><li>apps that need feature gating or fallback experiences.</li></ul><h3>Example: Feature Preflight Check</h3><p>Imagine you are building a face filter camera feature.</p><p>Before opening the feature, you may want to check:</p><ul><li>Does the device have a camera?</li><li>Does it have a gyroscope?</li><li>Does it have an accelerometer?</li><li>Is the battery level acceptable?</li><li>Is the network stable enough if the feature uploads media?</li></ul><p>Without NativeLens, you may need to combine multiple APIs and write your own decision rules.</p><p>With NativeLens, the goal is to make this simpler:</p><pre>final result = await NativeLens().analyzeCustomTask(<br>  taskName: &#39;Face Filter Camera&#39;,<br>  requirements: const NativeLensTaskRequirements(<br>    requiresCamera: true,<br>    requiredSensors: [&#39;gyroscope&#39;, &#39;accelerometer&#39;],<br>    minBatteryLevel: 20,<br>  ),<br>);</pre><pre>if (!result.canContinue) {<br>  // Show fallback UI or disable the feature.<br>}</pre><p>This is the main value of NativeLens:</p><blockquote><em>Check device readiness before the user reaches failure.</em></blockquote><h3>Current Limitations</h3><p>NativeLens is still growing.</p><p>Current limitations:</p><ul><li>Deep Android capability support remains the primary focus.</li><li>iOS support is currently foundational and safe-fallback oriented.</li><li>No macOS, Windows, Linux, or web implementation yet.</li></ul><p>These limitations are intentional and transparent. NativeLens focuses first on practical mobile device capability analysis.</p><h3>Future Feature Update Template</h3><p>Use this section whenever a new NativeLens feature is added.</p><h3>New Feature Name</h3><p>Short explanation of what the feature does.</p><pre>// Add code example here</pre><p>Why it matters:</p><ul><li>problem it solves,</li><li>when developers should use it,</li><li>what kind of apps benefit from it.</li></ul><p>Example result or output:</p><pre>// Add result example here</pre><h3>Final Thought</h3><p>NativeLens is built around one simple production idea:</p><blockquote><em>A Flutter app should understand the device before starting a feature that depends on the device.</em></blockquote><p>For developers building camera, media, sensor, network-heavy, or production-sensitive apps, NativeLens can work as a device readiness and compatibility layer.</p><p>It helps apps become more defensive, more adaptive, and more reliable across real devices.</p><p>If your Flutter feature depends on hardware, sensors, battery, network, media codecs, or platform capability, NativeLens can help you check first and fail less.</p><h3>Link</h3><ul><li>Package: <a href="https://pub.dev/packages/native_lens">https://pub.dev/packages/native_lens</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d7a2c086c91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Moved From a Self-Hosted GitHub Actions Runner on EC2 to a GitHub-Hosted SSH Deployment]]></title>
            <link>https://medium.com/elobyte-software/how-we-moved-from-a-self-hosted-github-actions-runner-on-ec2-to-a-github-hosted-ssh-deployment-97e7c0fe3e58?source=rss-a0bf9999dd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e7c0fe3e58</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Nazmul Haque Nahin]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 06:46:20 GMT</pubDate>
            <atom:updated>2026-06-09T06:16:01.187Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step guide to fixing server slowdown caused by running GitHub Actions self-hosted runner on the same EC2 instance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wmSahfO8wMVM5W3Z7Tl9OA.png" /></figure><h3>What problem we were facing</h3><p>We had a backend API running on an <strong>EC2 server</strong>.</p><p>To make deployment easy, we had also installed a <strong>GitHub Actions self-hosted runner</strong> on that same EC2 machine.<br>So one machine was doing two jobs:</p><ul><li>serving the live backend</li><li>running CI/CD workflow jobs</li></ul><p>At first, this looked nice because deployment was simple.<br> When code was pushed, GitHub Actions directly ran commands inside the EC2 server.</p><p>A simplified version of our old workflow looked like this:</p><pre>name: Demo API CICD<br><br>on:<br>  push:<br>    branches: [&quot;dev&quot;]<br><br>jobs:<br>  build:<br>    runs-on: self-hosted<br><br>    steps:<br>      - uses: actions/checkout@v4<br><br>      - uses: pnpm/action-setup@v4<br>        with:<br>          version: 8.6.12<br><br>      - uses: actions/setup-node@v4<br>        with:<br>          node-version: 20<br>          cache: pnpm<br><br>      - name: Install dependencies<br>        run: pnpm install --frozen-lockfile<br><br>      - name: Restart API<br>        run: pm2 restart demo-api</pre><p>This worked, but there was a problem.<br>When deployment ran, the same EC2 machine had to handle:</p><ul><li>app traffic</li><li>package installation</li><li>workflow execution</li><li>restart commands</li></ul><p>So the server got extra pressure during deployment.</p><p>That meant:</p><ul><li>the server could become slow</li><li>the live API could suffer</li><li>we might need more compute than necessary</li><li>AWS cost could grow for the wrong reason</li></ul><p>The real issue was simple:</p><p>our app server was also doing CI/CD work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6eSW54D8a4tEwojXvwyplg.png" /></figure><h3><strong>How we found our problem</strong></h3><p>At first, we only felt that the server was getting heavy.<br>So we started checking the setup properly.</p><blockquote>Check 1: confirm the self-hosted runner</blockquote><p>We looked in GitHub repository settings and confirmed that a self-hosted runner was connected.</p><p>We also checked inside EC2 and found the runner installation folder.</p><p>That told us the workflow was definitely running inside the EC2 machine.</p><blockquote>Check 2: inspect the running PM2 app</blockquote><p>Then we checked the running backend process:</p><pre>pm2 show demo-api</pre><p>That output showed something important:</p><ul><li>the app was not running from a normal app folder</li><li>it was running from the <strong>GitHub runner workspace</strong></li></ul><p>It looked like this:</p><pre>script path: /home/ubuntu/demo-actions-runner/_work/demo-api/demo-api/main.js<br>exec cwd: /home/ubuntu/demo-actions-runner/_work/demo-api/demo-api</pre><p>That was the real hidden problem.<br>So now we understood two things:</p><ol><li>the server was doing CI/CD work</li><li>the live app itself was tied to the runner workspace</li></ol><p>That meant if we removed the runner carelessly, we could even break the live backend. So we had to solve this carefully.</p><h3>What is an action runner, why we use it, and how it worked for us</h3><p>A <strong>GitHub Actions runner</strong> is just the machine that executes your workflow.For example, if GitHub sees this:</p><pre>runs-on: ubuntu-latest</pre><p>GitHub uses its own machine.<br>If it sees this:</p><pre>runs-on: self-hosted</pre><p>GitHub sends the job to your own registered machine.<br>Why people use it</p><p>We use runners because workflows need a machine to do things like:</p><ul><li>check out code</li><li>install dependencies</li><li>run tests</li><li>build the project</li><li>deploy the app</li></ul><h3>How it worked for us</h3><p>In our old setup:</p><ul><li>GitHub detected a push</li><li>GitHub sent the job to our EC2 self-hosted runner</li><li>the EC2 machine ran the workflow steps</li><li>PM2 restarted the backend</li></ul><p>So the flow looked like this:</p><pre>Push code -&gt; GitHub workflow starts -&gt; EC2 self-hosted runner executes job -&gt; PM2 restarts API</pre><p>This was simple, but it made our app server also behave like a CI worker. That was the core design problem.</p><h3>How we solved that issue</h3><p>We wanted to fix the issue with <strong>minimal risk</strong>. So we solved it in small steps.</p><blockquote><strong>Step 1: Move the app out of the runner workspace</strong></blockquote><p>Since the app was running from the runner workspace, our first goal was: <strong>move the running app into a normal stable folder . </strong>We created a new folder:</p><pre>mkdir -p /home/ubuntu/demo-app</pre><p>Then copied the current app files into it:</p><pre>cp -r /home/ubuntu/demo-actions-runner/_work/demo-api/demo-api/* /home/ubuntu/demo-app/</pre><p>We also copied the environment file:</p><pre>cp /home/ubuntu/demo-actions-runner/_work/demo-api/demo-api/.env /home/ubuntu/demo-app/.env</pre><p>Why this mattered:<br>- the app now had its own stable location<br>- it no longer depended on runner folders<br>- later we could safely remove the runner</p><blockquote><strong>Step 2: Start the app from the stable folder first</strong></blockquote><p>We did not replace the old process immediately. First, we started a second PM2 process from the new stable folder:</p><pre>cd /home/ubuntu/demo-app<br>pm2 start main.js --name demo-api-stable</pre><p>Then we verified it:</p><pre>pm2 show demo-api-stable</pre><p>We checked these lines:</p><pre>script path: /home/ubuntu/demo-app/main.js<br>exec cwd: /home/ubuntu/demo-app</pre><p>This gave us confidence that the app could run properly from the stable folder.</p><blockquote><strong>Step 3: Replace the old process safely</strong></blockquote><p>After confirming the stable process was working, we removed the old runner-based process:</p><pre>pm2 delete demo-api</pre><p>Then we renamed the new stable process back to the expected app name:</p><pre>pm2 restart demo-api-stable --name demo-api</pre><p>Then we saved PM2:</p><pre>pm2 save</pre><p>After this step, the live backend was no longer running from the runner workspace. That was the biggest fix.</p><blockquote><strong>Step 4: Change the workflow to GitHub-hosted runner</strong></blockquote><p>Now that the app had its own stable folder, we could move CI work out of EC2. <br>We changed this :</p><pre>runs-on: self-hosted</pre><p>to this:</p><pre>runs-on: ubuntu-latest</pre><p>That means:<br>- workflow jobs now run on GitHub’s machine<br>- EC2 stops doing CI work<br>- EC2 only serves the app</p><blockquote><strong>Step 5: Replace local restart with SSH deployment</strong></blockquote><p>Before, the workflow directly ran:</p><pre>- name: Restart API<br>  run: pm2 restart demo-api</pre><p>That worked only because the runner was inside EC2.</p><p>After moving to GitHub-hosted runner, this would no longer work directly. So we changed the deployment style:<br>- GitHub workflow runs on ubuntu-latest <br>- it connects to EC2 using SSH<br>- it copies files to the stable app folder<br>- then it restarts PM2 remotely</p><blockquote><strong>Step 6: Add SSH secrets</strong></blockquote><p>We added these GitHub repository secrets: <br>- EC2_HOST<br>- EC2_USER<br>- EC2_SSH_KEY</p><p>These were used so GitHub Actions could connect to EC2 securely.</p><blockquote><strong>Step 7: Final updated workflow</strong></blockquote><p>Here is the simplified final workflow we used with demo names:</p><pre>name: Demo API CICD<br><br>on:<br>  push:<br>    branches: [&quot;dev&quot;]<br><br>jobs:<br>  deploy:<br>    runs-on: ubuntu-latest<br>    strategy:<br>      matrix:<br>        node-version: [20.x]<br><br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br><br>      - name: Setup pnpm<br>        uses: pnpm/action-setup@v4<br>        with:<br>          version: 8.6.12<br><br>      - name: Setup Node.js<br>        uses: actions/setup-node@v4<br>        with:<br>          node-version: ${{ matrix.node-version }}<br>          cache: pnpm<br><br>      - name: Create .env file<br>        run: |<br>          cat &gt; .env &lt;&lt; EENV<br>          APP_ENV=${{ secrets.DEV_APP_ENV }}<br>          PORT=${{ secrets.DEV_PORT }}<br>          DB_HOST=${{ secrets.DEV_DB_HOST }}<br>          DB_USER=${{ secrets.DEV_DB_USER }}<br>          DB_PASSWORD=${{ secrets.DEV_DB_PASSWORD }}<br>          DB_NAME=${{ secrets.DEV_DB_NAME }}<br>          EENV<br><br>      - name: Install dependencies<br>        run: pnpm install --frozen-lockfile<br><br>      - name: Upload app files to EC2<br>        uses: appleboy/scp-action@v0.1.7<br>        with:<br>          host: ${{ secrets.EC2_HOST }}<br>          username: ${{ secrets.EC2_USER }}<br>          key: ${{ secrets.EC2_SSH_KEY }}<br>          source: &quot;assets,main.js,package.json,pnpm-lock.yaml,.env&quot;<br>          target: &quot;/home/ubuntu/demo-app&quot;<br><br>      - name: Restart app on EC2<br>        uses: appleboy/ssh-action@v1.0.3<br>        with:<br>          host: ${{ secrets.EC2_HOST }}<br>          username: ${{ secrets.EC2_USER }}<br>          key: ${{ secrets.EC2_SSH_KEY }}<br>          script: |<br>            cd /home/ubuntu/demo-app<br>            export NVM_DIR=&quot;$HOME/.nvm&quot;<br>            [ -s &quot;$NVM_DIR/nvm.sh&quot; ] &amp;&amp; . &quot;$NVM_DIR/nvm.sh&quot;<br>            pnpm install --frozen-lockfile<br>            pm2 restart demo-api --update-env</pre><blockquote><strong>Step 8: Test before cleanup</strong></blockquote><p>After updating the workflow, we pushed code and watched the action run.The workflow succeeded.Then we confirmed the app was still running from the stable folder:</p><pre>pm2 show demo-api</pre><p>And it showed:</p><pre>script path: /home/ubuntu/demo-app/main.js<br>exec cwd: /home/ubuntu/demo-app</pre><p>We also checked the frontend, and everything was still working.Only then did we clean up the old runner.</p><blockquote><strong>Step 9: Remove the self-hosted runner</strong></blockquote><p>Once we knew the new deployment flow worked, we removed the old self-hosted runner. First, stop the service:</p><pre>cd ~/demo-actions-runner<br>sudo ./svc.sh stop</pre><p>Then uninstall the service:</p><pre>sudo ./svc.sh uninstall</pre><p>Then remove the folder:</p><pre>rm -rf ~/demo-actions-runner</pre><p>Now the EC2 machine was fully free from runner responsibilities.</p><h3>Final result</h3><p>After the migration:</p><ul><li>the backend app runs from /home/ubuntu/demo-app</li><li>GitHub Actions runs on ubuntu-latest</li><li>EC2 is no longer doing CI jobs</li><li>deployment still happens automatically</li><li>PM2 restarts the app remotely through SSH</li><li>the server is cleaner and safer</li></ul><p>The new flow became:</p><pre>Push code -&gt; GitHub-hosted workflow starts -&gt; files copied to EC2 -&gt; PM2 restarts app in stable folder</pre><h3>Main lesson</h3><p>A self-hosted runner is not bad by itself.</p><p>The problem comes when the <strong>same server is both</strong>:</p><ul><li>the live application server</li><li>and the CI/CD runner</li></ul><p>That can create hidden load, tight coupling, and risky deployments.</p><p>The better solution for us was:</p><ul><li>keep the app in a stable folder</li><li>let GitHub-hosted runners do the CI work</li><li>use SSH only for deployment</li></ul><p>That gave us a much cleaner setup with less server pressure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97e7c0fe3e58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elobyte-software/how-we-moved-from-a-self-hosted-github-actions-runner-on-ec2-to-a-github-hosted-ssh-deployment-97e7c0fe3e58">How We Moved From a Self-Hosted GitHub Actions Runner on EC2 to a GitHub-Hosted SSH Deployment</a> was originally published in <a href="https://medium.com/elobyte-software">elobyte-Software</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Practical Nx Monorepo Blueprint: Secrets Sync, Fast CI, and Safer Deployments]]></title>
            <link>https://medium.com/elobyte-software/a-practical-nx-monorepo-blueprint-secrets-sync-fast-ci-and-safer-deployments-64bf8c4a9084?source=rss-a0bf9999dd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/64bf8c4a9084</guid>
            <category><![CDATA[nx-monorepo]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[hashicorp-vault]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Nazmul Haque Nahin]]></dc:creator>
            <pubDate>Sat, 14 Feb 2026 18:25:27 GMT</pubDate>
            <atom:updated>2026-06-09T06:13:11.461Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Env Chaos to Repeatable Releases: Nx Affected + Vault + Render at Scale</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iVVCpAtqnxtbE2Rm7dI9yw.png" /><figcaption><em>A story-driven guide to reducing env drift, speeding up CI, and deploying multiple Node/Express apps with confidence</em></figcaption></figure><h3>The day “just add it to .env” stopped working</h3><p>We run multiple Node/Express TypeScript apps, today it’s about our 2 apps, and it won’t stay at two. For a while, secrets and deployments were… fine. Then the team grew, environments multiplied, and “fine” turned into:</p><ul><li>secrets scattered across laptops, CI variables, and platform dashboards</li><li>inconsistent .env values between dev/staging/prod</li><li>deployments that worked <em>only</em> if you remembered the latest steps</li><li>repeated CI work across apps that didn’t even change</li></ul><p>That was the moment we stopped treating this as “DevOps chores” and started treating it as architecture.</p><p>This post is the practical story of how we used an <strong>Nx monorepo + pnpm</strong>, <strong>HashiCorp Vault</strong>, and a <strong>clean deployment repo</strong> pattern to make secrets and deployments boring again, while cutting CI time using <strong>Nx affected + caching</strong>.</p><h3>What Nx monorepo is (for backend/fullstack devs)</h3><p>If you’ve used a monorepo before, Nx is the version that actually understands your codebase as a graph.</p><p>In plain terms:</p><ul><li>Nx manages multiple apps/libs in one repo.</li><li>It builds a dependency graph (what depends on what).</li><li>It can run tasks only for what changed (“affected”).</li><li>It supports caching so you don’t redo work unnecessarily.</li></ul><p>So instead of “run CI for everything,” it becomes:<br><strong>only run what matters, in the right order, with reproducibility baked in.</strong></p><h3>Why we chose Nx monorepo over separate repos</h3><p>We could have split <strong>app-1</strong> and <strong>app-2</strong> into separate repositories. It’s a common move. But our reality looked like this:</p><ul><li>shared standards (linting, TS config, logging conventions)</li><li>shared infra patterns (same secrets strategy, same deploy pattern)</li><li>shared tooling (scripts, CI templates, utility libs)</li><li>teams working across services</li></ul><p>Separate repos meant duplicated effort and drift across repos. A monorepo meant:</p><ul><li>one “golden path” for build/deploy</li><li>shared scripts and targets</li><li>one CI system with consistent enforcement</li><li>easy scaling from 2 apps to 10 without multiplying pipelines</li></ul><p>Nx made the monorepo manageable, not messy.</p><h3>The secret management pain before Vault</h3><p>Before Vault, secrets typically lived in a mix of places:</p><ul><li>.env files passed around privately</li><li>GitHub Actions secrets, but with inconsistent naming</li><li>Render environment variables updated manually</li><li>random “temporary” secrets in Slack (it happens)</li></ul><p>The problems weren’t theoretical. They were operational:</p><ul><li><strong>env drift:</strong> prod differed from staging, staging differed from dev, nobody knew why</li><li><strong>secret sprawl:</strong> too many sources of truth</li><li><strong>unsafe updates:</strong> changing a secret required platform clicking + memory of steps</li><li><strong>non-repeatable deploys:</strong> CI didn’t fully represent reality</li></ul><p>We needed one source of truth for secrets <strong>and</strong> a consistent way to apply them everywhere.</p><h3>How Vault + Nx targets solved secret sprawl and env drift</h3><p>Vault became our source of truth. Nx became the orchestrator.</p><p>We implemented a set of Nx targets that turn secrets and deployment into a pipeline:</p><ul><li>vault: fetch environment secrets from Vault and generate an env file (or export variables)</li><li>render-sync: push those env vars into Render using the Render API</li><li>build: produce dist for Express or NestJS apps</li><li>prune: prepare minimal workspace + lockfile for a clean artifact</li><li>deploy: push artifact to a clean deployment repo branch and trigger deploy</li></ul><p>The key idea: <strong>secrets management is a first-class build step</strong>, not a side quest.</p><h4>Example Nx target flow (conceptual)</h4><pre>// apps/erp/project.json (conceptual)<br>{<br>  &quot;targets&quot;: {<br>    &quot;vault&quot;: { &quot;executor&quot;: &quot;nx:run-commands&quot;, &quot;options&quot;: { &quot;command&quot;: &quot;ts-node scripts/fetch-vault-secrets.ts&quot; } },<br>    &quot;render-sync&quot;: { &quot;executor&quot;: &quot;nx:run-commands&quot;, &quot;options&quot;: { &quot;command&quot;: &quot;ts-node scripts/render-sync.ts&quot; } },<br>    &quot;build&quot;: { &quot;dependsOn&quot;: [&quot;vault&quot;], &quot;executor&quot;: &quot;@nx/esbuild:esbuild&quot;, &quot;options&quot;: { &quot;outputPath&quot;: &quot;dist/apps/erp&quot; } },<br>    &quot;prune&quot;: { &quot;dependsOn&quot;: [&quot;build&quot;], &quot;executor&quot;: &quot;nx:run-commands&quot;, &quot;options&quot;: { &quot;command&quot;: &quot;node scripts/prune-artifact.js&quot; } },<br>    &quot;deploy&quot;: { &quot;dependsOn&quot;: [&quot;render-sync&quot;, &quot;prune&quot;], &quot;executor&quot;: &quot;nx:run-commands&quot;, &quot;options&quot;: { &quot;command&quot;: &quot;node scripts/deploy-clean-repo.js&quot; } }<br>  }<br>}</pre><h4>What “render-sync” actually does</h4><p>The render-sync step is where a lot of teams stay manual. We didn’t.</p><p>High-level logic:</p><ol><li>Fetch secrets from Vault (already done by vault)</li><li>Convert env data into the format Render expects</li><li>Call Render API to upsert env vars for the service</li><li>Trigger a deploy (or let Render redeploy on env update, depending on settings)</li></ol><p>Pseudo snippet:</p><pre>// scripts/render-sync.ts (pseudo)<br>const env = loadEnvFromGeneratedFile(); // output of vault step<br>await render.updateServiceEnv({<br>  serviceId: process.env.RENDER_SERVICE_ID,<br>  envVars: Object.entries(env).map(([key, value]) =&gt; ({ key, value }))<br>});<br>await render.triggerDeploy({ serviceId: process.env.RENDER_SERVICE_ID });</pre><p>The win: <strong>Vault is the source of truth; Render is always synced; deployments are repeatable.</strong></p><h3>Before vs after (what actually changed)</h3><p>Area Before After Source of truth for secrets many places Vault only Updating Render env manual clickingnx run &lt;app&gt;:render-syncDeploy steps tribal knowledge encoded in Nx targets CI scope builds everything nx affected builds only changed apps Debugging releases “what changed?” graph + deterministic pipeline</p><h3>Nx affected + caching: the CI upgrade you feel immediately</h3><p>Once secrets and deploy steps were encoded as targets, CI was the next bottleneck.<br>Nx affected + caching changed the economics:</p><ul><li>only build/test/deploy apps that changed</li><li>reuse cached outputs for unchanged tasks</li><li>keep CI fast even as the repo grows</li></ul><p>In GitHub Actions, the big shift is:</p><pre>pnpm nx affected -t lint build deploy --base=origin/main --head=HEAD</pre><p>This works because Nx knows:</p><ul><li>what projects changed</li><li>what depends on what</li><li>which tasks can be cached</li></ul><p>For us, this wasn’t a micro-optimization. It was the difference between:</p><ul><li>“CI is always slow, schedule around it”</li><li>and “CI is fast enough to be part of your feedback loop”</li></ul><h3>Why we use a separate clean deployment repo</h3><p>This is the part people debate. We deploy via a separate “clean deploy repo” branch (or separate repo entirely) that contains only what the platform needs.</p><p><strong>Deployment pattern:</strong></p><ol><li>Build in the monorepo</li><li>Prepare clean dist artifact</li><li>Push artifact to clean repo/branch</li><li>Trigger Render deploy via API</li></ol><p>Why?</p><ul><li><strong>security &amp; simplicity:</strong> the deploy surface is smaller (no monorepo history, no dev tooling)</li><li><strong>fewer platform surprises:</strong> Render sees a minimal repo with predictable structure</li><li><strong>dependency control:</strong> we can prune workspace modules + lockfile to exactly what’s needed</li><li><strong>separation of concerns:</strong> dev repo stays dev-focused; deploy repo stays runtime-focused</li></ul><p>It also makes future expansion easier:<br>- Render today<br>- AWS EC2 later (same artifact, different deploy target)</p><h3>Architecture diagram (described in words)</h3><p>Imagine a left-to-right pipeline with 4 blocks:</p><p><strong>Developer + GitHub</strong></p><ul><li>Dev pushes changes to monorepo (Nx + pnpm)</li><li>GitHub Actions starts workflow</li></ul><p><strong>Nx CI Orchestrator</strong></p><ul><li>Nx computes “affected” graph</li><li>Runs targets per app: vault → render-sync → build → prune → deploy</li><li>Uses caching to skip unchanged work</li></ul><p><strong>Secrets + Hosting</strong></p><ul><li>Vault stores environment secrets per app and per environment</li><li>Render receives synced env vars via API and stores them in the service settings</li></ul><p><strong>Clean Deploy Repo</strong></p><ul><li>CI pushes only dist + minimal runtime files to a clean branch/repo</li><li>Render deploys from that clean repo</li><li>Result: running services for erp and billing</li></ul><p>The important arrows:</p><ul><li>Vault → Nx targets (fetch secrets)</li><li>Nx targets → Render API (sync env + trigger deploy)</li><li>Nx build output → clean deploy repo → Render deploy</li></ul><h3>Why this architecture is best for our scenario</h3><p>This approach fits when you have:</p><ul><li>multiple apps that share standards and tooling</li><li>multiple environments where drift is costly</li><li>a team where “manual platform steps” don’t scale</li><li>a need for safer releases and predictable rollbacks</li></ul><p>The main reason it worked for us:<br><strong>we stopped treating deployment as a script and started treating it as a product.</strong></p><p>Nx gave us the structure to keep that product maintainable.</p><h3>Tradeoffs and limitations (the honest part)</h3><p>This setup isn’t free.</p><ul><li><strong>More upfront engineering:</strong> you’re building a pipeline, not copying a template.</li><li><strong>You must design secret naming conventions:</strong> Vault paths + env var naming needs discipline.</li><li><strong>Render API sync adds coupling:</strong> your pipeline depends on platform APIs behaving as expected.</li><li><strong>Debugging can become “pipeline debugging”:</strong> you’ll want good logs and dry-run modes.</li><li><strong>Clean repo flow can confuse newcomers:</strong> document it clearly, or people will fight it.</li></ul><p>If your team is small and your deployments are rare, this can be overkill. But if you’re scaling apps and environments, it pays back quickly.</p><h3>Mistakes I made during setup (so you don’t repeat them)</h3><p><strong>I under-invested in naming conventions</strong></p><ul><li>Fix: define a strict env key convention early (APP__SCOPE__NAME) and stick to it.</li></ul><p><strong>I didn’t build “diff visibility” at first</strong></p><ul><li>Fix: before syncing env, print a redacted diff summary (added/removed/changed keys).</li></ul><p><strong>I coupled targets too tightly too early</strong></p><ul><li>Fix: keep targets composable. Let CI decide which chain to run (render-sync might be skipped locally).</li></ul><p><strong>I skipped rollback thinking</strong></p><ul><li>Fix: version artifacts in the clean deploy repo (tags or commit messages), so “roll back” is trivial.</li></ul><p><strong>I didn’t add guardrails</strong></p><ul><li>Fix: block deploy if secrets fetch fails, validate required keys, and fail fast.</li></ul><h3>Practical takeaways + adoption checklist</h3><p>If you want to adopt this pattern, here’s the checklist I’d actually follow:</p><p><strong>Repo + tooling</strong></p><p>Nx workspace created and apps split (<em>apps/erp</em>, <em>apps/billing</em>, <em>apps/email</em>)</p><ul><li>pnpm workspace configured</li><li>consistent TypeScript + lint rules</li></ul><p><strong>Secrets</strong></p><ul><li>Vault path scheme defined (per app, per environment)</li><li>script to fetch secrets (vault target)</li><li>generated env format decided (.env.generated or process export)</li><li>required key validation + redacted logs</li></ul><p><strong>Deploy</strong></p><ul><li>build produces clean dist</li><li>prune creates minimal deploy context (workspace deps + lockfile strategy)</li><li>clean deploy repo/branch strategy documented</li><li>Render API sync (render-sync) implemented and tested</li><li>deploy trigger via Render API</li></ul><p><strong>CI</strong></p><ul><li>GitHub Actions uses nx affected</li><li>caching enabled</li><li>environment protections (prod approvals, branch rules)</li></ul><h3>who should and shouldn’t use this approach ?</h3><p>This approach is great if you:</p><ul><li>run multiple services/apps with shared standards</li><li>want one source of truth for secrets (Vault)</li><li>care about repeatable releases and minimizing platform clicking</li><li>want CI cost and time to scale reasonably as the repo grows</li></ul><p>You probably shouldn’t use it if you:</p><ul><li>have a single app and one environment</li><li>deploy manually once a month and it’s fine</li><li>don’t have bandwidth to maintain a pipeline like a product .<br>No app or idea is small. But if you are still in the mvp or demo stage you may skip this</li></ul><p>For us, Nx + Vault + a clean deploy repo turned deployments into a consistent, auditable system — and made it easy to grow from “two apps” to “many apps” without rewriting everything.</p><p>If you’re feeling the pain of env drift and CI bloat, this is one of the cleanest paths I’ve found to regain control.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64bf8c4a9084" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elobyte-software/a-practical-nx-monorepo-blueprint-secrets-sync-fast-ci-and-safer-deployments-64bf8c4a9084">A Practical Nx Monorepo Blueprint: Secrets Sync, Fast CI, and Safer Deployments</a> was originally published in <a href="https://medium.com/elobyte-software">elobyte-Software</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From EC2 to Lambda: How We Deployed a Cost-Effective PDF Service from ECR | Part : 05]]></title>
            <link>https://medium.com/elobyte-software/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-05-464a9da02a3d?source=rss-a0bf9999dd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/464a9da02a3d</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[pdf-converter]]></category>
            <dc:creator><![CDATA[Nazmul Haque Nahin]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 16:46:00 GMT</pubDate>
            <atom:updated>2025-12-07T05:45:20.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>From EC2 to Lambda: How We Deployed a Cost-Effective PDF Service from ECR | Part: 05</h3><h4>The Final Journey: From Your Laptop to AWS Lambda</h4><p>In <a href="https://medium.com/elobyte-software/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-04-fb31157b6085"><strong><em>previous part</em></strong></a> we talked about building docker image. Now..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rd4Xkh_TcFXs0E0kT1YM-Q.png" /></figure><h4>Step 1: Repo creation in <strong>Amazon ECR (Elastic Container Registry)</strong></h4><ul><li>Go to AWS Console → search “ECR.”</li><li>Click <strong>Create Repository</strong></li><li>Name it pdf-service → click <strong>Create</strong></li></ul><h4>Step 2: Push Your Image to ECR</h4><p>To push your Docker image into <strong>Amazon ECR (Elastic Container Registry)</strong>, you’ll use the AWS CLI and Docker.</p><ul><li>Inside your new repo, click <strong>View push commands</strong></li><li>AWS shows you copy-paste commands like:</li></ul><ol><li>Login Docker to AWS</li><li>Build your image (docker build)</li><li>Tag the image with your repo URI</li><li>Push the image</li></ol><p>Run them in your terminal.</p><blockquote>Commands To Push Image:</blockquote><ol><li>Retrieve an authentication token and authenticate your Docker client to your registry.</li></ol><ul><li>&lt;region&gt; = your AWS region (for example: us-east-1).</li><li>&lt;account_id&gt; = your AWS account ID.</li></ul><pre>aws ecr get-login-password --region &lt;region&gt; | docker login --username AWS --password-stdin &lt;account_id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com</pre><p>2. Build your Docker image using the following command.</p><pre>docker build -t pdf-service .</pre><p>3. After the build completes, tag your image so you can push the image to this repository:</p><pre>docker tag pdf-service:latest &lt;account_id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/pdf-service:latest</pre><p>4. Run the following command to push this image to your newly created AWS repository:</p><pre>docker push &lt;account_id&gt;.dkr.ecr.&lt;region&gt;.amazonaws.com/pdf-service:latest</pre><h4>Step 3: Create a Lambda Function</h4><ul><li>Go to AWS Console → search “Lambda.”</li><li>Click <strong>Create Function</strong></li><li>Choose <strong>Container Image</strong></li><li>Select the ECR image you just pushed</li><li>Give it a name → pdf-service-lambda</li><li>Pick an IAM role (permissions for Lambda to run)</li><li>Click <strong>Create</strong></li></ul><p>Now your service is alive in the cloud.</p><h4>Step 4: Test It</h4><ul><li>Open your Lambda function → click <strong>Test</strong></li><li>Add a simple event → hit Test</li><li>Lambda spins up your container → you see logs</li><li>Connect API Gateway → hit /health endpoint → you get { &quot;ok&quot;: true }</li></ul><p>Your serverless PDF factory works !!</p><p>Cheers!! I hope now you know how to create, dockerize, and deploy a PDF service into Lambda!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=464a9da02a3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elobyte-software/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-05-464a9da02a3d">From EC2 to Lambda: How We Deployed a Cost-Effective PDF Service from ECR | Part : 05</a> was originally published in <a href="https://medium.com/elobyte-software">elobyte-Software</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From EC2 to Lambda: How We Deployed a Cost-Effective PDF Service from ECR | Part : 03]]></title>
            <link>https://medium.com/@nahin.cdr/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-03-412f957d7be6?source=rss-a0bf9999dd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/412f957d7be6</guid>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[gotenberg]]></category>
            <category><![CDATA[html-to-pdf-converter]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Nazmul Haque Nahin]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 10:32:18 GMT</pubDate>
            <atom:updated>2025-12-07T05:24:53.845Z</atom:updated>
            <content:encoded><![CDATA[<h3>From EC2 to Lambda: How We Deployed a Cost-Effective PDF Service from ECR | Part : 03</h3><h4>The “PDF Gateway” — Your Simple API to Gotenberg</h4><p>In <a href="https://medium.com/elobyte-software/building-a-pdf-gateway-with-docker-lambda-and-gotenberg-de4e3bf74658?postPublishedType=repub"><strong>previous part</strong></a> we talked about the architecture and visualize things. Now..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Y7QwsDQNTMS4IvVlBUIiw.png" /></figure><blockquote><strong>Imagine this:</strong> you don’t want your frontend or other apps to deal with Gotenberg’s multipart forms and low-level details.<br>=&gt; So we build a <strong>tiny Node.js server</strong> that takes <strong>clean JSON input</strong> and gives you back a <strong>PDF</strong>. Easy, right?</blockquote><pre>[ Your App / Frontend ]<br>          │  JSON<br>          ▼<br>   [ PDF Gateway (Express) ]<br>          │  form-data (behind the scenes)<br>          ▼<br> [ Gotenberg (Chromium/LibreOffice) ]<br>          │  PDF<br>          ▼<br>         You </pre><h4>How It Works (in plain words)</h4><ol><li><strong>Send a request</strong> with your HTML (and a few options if you want).</li><li><strong>Gateway prepares it</strong> in the format Gotenberg understands.</li><li><strong>Gotenberg converts</strong> the HTML → PDF.</li><li><strong>Gateway returns</strong> the PDF file to you.</li></ol><p>The Core Endpoint</p><pre>POST /generate</pre><h4>Input (JSON)</h4><pre>{<br>  &quot;html&quot;: &quot;&lt;h1&gt;Hello PDF&lt;/h1&gt;&quot;,<br>    &quot;options&quot;: {<br>        &quot;printBackground&quot;: true,<br>        &quot;landscape&quot;: false,<br>        &quot;waitDelay&quot;: &quot;200ms&quot;<br>    }<br>}</pre><h4>Output</h4><p>A nice shiny <strong>PDF file</strong> (content-type: application/pdf).</p><h4>The Express Code</h4><p>Here’s the <strong>heart of the gateway</strong>:</p><pre>app.post(&quot;/generate&quot;, async (req, res) =&gt; {<br>  const { html, options = {} } = req.body || {};<br>  if (!html) return res.status(400).json({ error: &quot;Need `html` string&quot; });<br><br>  const form = new FormData();<br>  form.append(&quot;files&quot;, Buffer.from(html, &quot;utf8&quot;), { filename: &quot;index.html&quot; });<br>  if (options.landscape) form.append(&quot;landscape&quot;, &quot;true&quot;);<br>  if (options.printBackground) form.append(&quot;printBackground&quot;, &quot;true&quot;);<br>  if (options.pageRanges) form.append(&quot;pageRanges&quot;, options.pageRanges);<br><br>  const gotenResp = await axios.post(<br>    `${GOTENBERG_URL}/forms/chromium/convert/html`,<br>    form,<br>    { responseType: &quot;arraybuffer&quot;, headers: form.getHeaders() }<br>  );<br><br>  res.setHeader(&quot;Content-Type&quot;, &quot;application/pdf&quot;);<br>  res.send(Buffer.from(gotenResp.data));<br>});</pre><p>Notice how:</p><ul><li>You <strong>send JSON</strong> → it <strong>wraps it into a form</strong> → Gotenberg does the magic.</li><li>You don’t have to care about multipart forms at all.</li></ul><h4>Here is our full code :</h4><pre>import express from &quot;express&quot;;<br>import axios from &quot;axios&quot;;<br>import FormData from &quot;form-data&quot;;<br><br>const app = express();<br>app.use(express.json({ limit: &quot;10mb&quot; }));<br><br>/** <br>Gotenberg server will run at port 3000 in that environment locally<br>**/<br>const GOTENBERG_URL = process.env.GOTENBERG_URL || &quot;http://localhost:3000&quot;;<br><br>/**<br> * POST /generate<br> * Body (JSON): { html: string, options?: { landscape?: boolean, printBackground?: boolean, pageRanges?: string, waitDelay?: number } }<br> * Returns: PDF (application/pdf)<br> */<br>app.post(&quot;/generate&quot;, async (req, res) =&gt; {<br>  try {<br>    const { html, options = {} } = req.body || {};<br>    if (!html || typeof html !== &quot;string&quot;) {<br>      return res.status(400).json({ error: &quot;Provide `html` as a string.&quot; });<br>    }<br><br>    // Build multipart for Gotenberg: /forms/chromium/convert/html<br>    const form = new FormData();<br><br>    // index.html part (Gotenberg expects an HTML file)<br>    form.append(&quot;files&quot;, Buffer.from(html, &quot;utf8&quot;), { filename: &quot;index.html&quot;, contentType: &quot;text/html&quot; });<br><br>    // Optional Chromium flags supported by Gotenberg form routes (examples)<br>    // See docs for exact form fields you want to use (e.g., margin, paper width/height, etc.)<br>    if (options.landscape !== undefined) form.append(&quot;landscape&quot;, String(!!options.landscape));<br>    if (options.printBackground !== undefined) form.append(&quot;printBackground&quot;, String(!!options.printBackground));<br>    if (options.pageRanges) form.append(&quot;pageRanges&quot;, options.pageRanges);<br>    if (options.waitDelay !== undefined) form.append(&quot;waitDelay&quot;, options.waitDelay);// ms<br><br>    // Send to Gotenberg<br>    const url = `${GOTENBERG_URL}/forms/chromium/convert/html`;<br>    <br><br>    const gotenResp = await axios.post(url, form, {<br>      responseType: &quot;arraybuffer&quot;,<br>      headers: form.getHeaders(),<br>      // Increase timeout for complex pages if you like<br>      timeout: 90000<br>    });<br>    res.setHeader(&quot;Content-Type&quot;, &quot;application/pdf&quot;);<br>  <br>    res.setHeader(&quot;Content-Length&quot;, gotenResp.data.length);<br>    console.log(`PDF size: ${gotenResp.data.length} bytes`);<br><br>    res.setHeader(&quot;Content-Disposition&quot;, &#39;inline; filename=&quot;document.pdf&quot;&#39;);<br><br>    res.status(200).send(Buffer.from(gotenResp.data));<br>  } catch (err) {<br>    const status = err.response?.status || 500;<br>    const msg = err.response?.data?.toString?.() || err.message;<br>    res.status(status).json({ error: &quot;Conversion failed&quot;, detail: msg });<br>  }<br>});<br><br>app.get(&quot;/health&quot;, (_req, res) =&gt; res.json({ ok: true }));<br><br>app.listen(8080, () =&gt; {<br>  console.log(&quot;PDF JSON gateway listening on :8080&quot;);<br>});</pre><h4>Why This Matters</h4><ul><li><strong>Cleaner API</strong> → Frontend/clients only send JSON.</li><li><strong>Pluggable</strong> → Swap in different PDF engines later if you want.</li><li><strong>Serverless ready</strong> → Perfect fit for AWS Lambda (as we saw in the Dockerfile).</li></ul><p>Next, in <a href="https://medium.com/@nahin.cdr/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-04-fb31157b6085"><strong><em>Part : 4</em></strong></a> we’ll connect this gateway with our<strong> Docker + Lambda setup</strong> so you have a<strong> </strong>fully<strong> serverless PDF servic</strong>e running in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=412f957d7be6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From EC2 to Lambda: How We Deployed a Cost-Effective PDF Service from ECR | Part : 04]]></title>
            <link>https://medium.com/elobyte-software/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-04-fb31157b6085?source=rss-a0bf9999dd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb31157b6085</guid>
            <category><![CDATA[aws-ecr]]></category>
            <category><![CDATA[pdf-converter]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-cost-optimization]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Nazmul Haque Nahin]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 05:31:28 GMT</pubDate>
            <atom:updated>2025-12-07T05:41:35.136Z</atom:updated>
            <content:encoded><![CDATA[<h3>From EC2 to Lambda: How We Deployed a Cost-Effective PDF Service from ECR | Part: 04</h3><h4>Dockerfile and Code | Pdf-service | AWS Lambda</h4><p>In <a href="https://medium.com/@nahin.cdr/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-03-412f957d7be6"><strong><em>previous part</em></strong></a> we talked about express code part. Now..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qPcXLg1iDK6ubs1W" /></figure><h3>Building Docker Image:</h3><p>To deploy this service on AWS Lambda, we needed to <strong>containerize</strong> it using Docker. This process allows us to run our Node.js service in a lightweight, reproducible environment that can be easily deployed to Lambda.</p><p>Here’s an overview of the Docker image build process:</p><ul><li><strong>Base Image</strong>: The Dockerfile starts by using the node:20-slim image, which provides a minimal environment for running Node.js.</li><li><strong>Gotenberg Integration</strong>: It then adds the <strong>Gotenberg runtime</strong> that includes Chromium and LibreOffice.</li><li><strong>Lambda Web Adapter</strong>: The image integrates the <strong>Lambda Web Adapter</strong>, which enables the server to run as an AWS Lambda function.</li></ul><p>The entire service is bundled into this container, allowing for a seamless deployment to Lambda.</p><p>Now, Lets go with me to image building process step by step! Why and how we add each and every line in our dockerfile.</p><h3>1. Bring Node.js runtime</h3><pre>FROM node:20-slim AS nodebin</pre><p>We start with a lightweight <strong>Node.js 20</strong> image. This is only a helper stage, we’ll copy Node.js from here later.</p><h3>2. Use Gotenberg as the base image</h3><pre>FROM gotenberg/gotenberg:8</pre><p>This is our <strong>main image</strong>. Gotenberg already includes:</p><ul><li><strong>Chromium</strong> → for rendering HTML</li><li><strong>LibreOffice</strong> → for converting office docs</li></ul><p>Together, they power the PDF generation engine.</p><h3><strong>3. Add AWS Lambda Web Adapter</strong></h3><pre>COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:0.9.1 \<br>  /lambda-adapter /opt/extensions/lambda-adapter</pre><p><strong>Lambda Web Adapter Integration:</strong><br>The service is deployed on <strong>AWS Lambda</strong>, with the <strong>Lambda Web Adapter</strong> connecting the Express server to Lambda. The <strong>Lambda Web Adapter</strong> is a tool that allows <strong>AWS Lambda</strong> to act as a <strong>web server</strong>. Normally, AWS Lambda functions cannot handle HTTP requests directly, but the Lambda Web Adapter bridges that gap by enabling the Lambda function to accept and respond to HTTP traffic.</p><p>In short, the <strong>Lambda Web Adapter</strong> acts like a translator.<br>It takes incoming <strong>HTTP requests</strong> and adapts them so the app runs smoothly inside <strong>AWS Lambda</strong></p><blockquote>How it Works:</blockquote><p><strong>a) Proxy for HTTP Requests</strong>: The Lambda Web Adapter listens for incoming HTTP requests (like POST /generate) and routes them to the Lambda function.</p><p><strong>b) Express Server Integration</strong>: It allows <strong>Express.js</strong> applications to run seamlessly in AWS Lambda, handling routing and request processing just like a normal web server.</p><p><strong>c) Scalable and Cost-Effective</strong>: Since Lambda only runs when triggered, you only pay for the actual compute time used, making it a cost-effective solution compared to running a traditional server.</p><h3>4. Copy Node.js into this image</h3><pre>USER root<br>COPY --from=nodebin /usr/local/ /usr/local/</pre><p>Here, we copy Node.js from the first stage (nodebin) into this final image.<br>This allows us to run our Node.js <strong>gateway service</strong> inside Lambda.</p><h3>5. Install and copy the gateway</h3><pre>WORKDIR /opt/gateway<br>COPY gateway/package*.json ./<br>RUN npm ci --omit=dev<br>COPY gateway/ ./</pre><ul><li>Switch working directory to /opt/gateway</li><li>Copy package.json and install only <strong>production dependencies</strong></li><li>Copy the actual Node.js gateway code</li></ul><p>This is where our <strong>API logic</strong> lives.</p><h3>6. Drop root privileges</h3><pre>USER gotenberg</pre><p>Always safer to run containers as a non-root user.Here, we switch to Gotenberg’s built-in safe user.</p><h3>7. Configure the Lambda Web Adapter</h3><pre>ENV AWS_LWA_PORT=8080<br>ENV AWS_LWA_READINESS_CHECK_PATH=/health<br>ENV AWS_LWA_ENABLE_COMPRESSION=true</pre><ul><li>Expose service on <strong>port 8080</strong></li><li>Set up the health check on /health</li><li>Enable response compression for faster performance</li></ul><h3>8. Run Gotenberg + Node.js gateway</h3><pre>CMD [&quot;/bin/sh&quot;,&quot;-lc&quot;,&quot;gotenberg &amp; node /opt/gateway/server.js&quot;]</pre><p>Think of this line as the <strong>“startup script”</strong> for your container.</p><pre>Container starts<br>      │<br>      ▼<br> ┌─────────────┐<br> │  /bin/sh    │  ← opens a shell (like a small control room)<br> │   -lc       │<br> └─────────────┘<br>      │<br>      ▼<br> ┌─────────────┐<br> │ Gotenberg   │  ← PDF engine starts in background<br> │   (&amp;)       │<br> └─────────────┘<br>      │<br>      ▼<br> ┌──────────────────────────┐<br> │ Node.js (server.js)      │  ← Express gateway runs in foreground<br> │ Keeps container alive    │<br> └──────────────────────────┘</pre><ol><li><strong>/bin/sh -lc</strong></li></ol><ul><li>Opens a small <strong>shell (command box)</strong> inside the container.</li><li>-l = acts like a <strong>login shell</strong> (loads environment settings).</li><li>-c = tells it to <strong>run the next commands</strong>.</li></ul><p>2. <strong>gotenberg &amp;</strong></p><ul><li>Starts the <strong>Gotenberg engine</strong> (the PDF conversion engine).</li><li>The &amp; means “run this in the <strong>background</strong>,” so it doesn’t block the next task.</li></ul><p>3. <strong>node /opt/gateway/server.js</strong></p><ul><li>Starts your <strong>Node.js Express gateway</strong>.</li><li>This one runs in the <strong>foreground</strong>, meaning it stays active and keeps the container alive.</li><li>handles requests and talks to Gotenberg</li></ul><p>The container finally runs <strong>two services together</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRGO-UfhMhgCVSNwQ8YkBg.png" /></figure><h3>In Short</h3><p>This Dockerfile combines:</p><ul><li><strong>Gotenberg</strong> → PDF engine (Chromium + LibreOffice)</li><li><strong>Node.js Gateway</strong> → API to talk with Gotenberg</li><li><strong>Lambda Web Adapter</strong> → makes it work seamlessly in AWS Lambda</li></ul><h3>Our Final Dockerfile:</h3><pre># --- Stage: bring Node.js runtime ---<br>FROM node:20-slim AS nodebin<br><br># --- Final image: Gotenberg runtime (Chromium + LibreOffice) ---<br>FROM gotenberg/gotenberg:8<br><br># Lambda Web Adapter (HTTP -&gt; Lambda)<br>COPY --from=public.ecr.aws/awsguru/aws-lambda-adapter:0.9.1 \<br>  /lambda-adapter /opt/extensions/lambda-adapter<br><br># Add Node.js from the node image<br>USER root<br>COPY --from=nodebin /usr/local/ /usr/local/<br><br><br><br># Install your gateway deps<br>WORKDIR /opt/gateway<br>COPY gateway/package*.json ./<br>RUN npm ci --omit=dev<br>COPY gateway/ ./<br><br># Back to non-root runtime user<br>USER gotenberg<br><br># Lambda Web Adapter config: expose the gateway on 8080, health at /health<br>ENV AWS_LWA_PORT=8080<br>ENV AWS_LWA_READINESS_CHECK_PATH=/health<br>ENV AWS_LWA_ENABLE_COMPRESSION=true<br><br><br>CMD [&quot;/bin/sh&quot;,&quot;-lc&quot;,&quot;gotenberg &amp; node /opt/gateway/server.js&quot;]</pre><p>In <a href="https://medium.com/@nahin.cdr/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-05-464a9da02a3d"><strong><em>Part:05,</em></strong> </a>we will see how to create a lambda function, create a repo in ECR(Elastic Container Registry), then push our image to it, and deploy the image in Lambda.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb31157b6085" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elobyte-software/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-04-fb31157b6085">From EC2 to Lambda: How We Deployed a Cost-Effective PDF Service from ECR | Part : 04</a> was originally published in <a href="https://medium.com/elobyte-software">elobyte-Software</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From EC2 to Lambda: How We Deployed a Cost-Effective PDF Service from ECR | Part :]]></title>
            <link>https://medium.com/elobyte-software/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-30972d277235?source=rss-a0bf9999dd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/30972d277235</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[pdf-conversion-services]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Nazmul Haque Nahin]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 06:44:57 GMT</pubDate>
            <atom:updated>2025-11-30T18:15:37.456Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>How We Deployed a Cost-Effective PDF Service in Lambda from ECR | Part : 01</strong></h3><h4>Shifting from EC2 to Lambda | Cost optimization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iavjhl2a2n9Mq-xuzg4Jtg.png" /></figure><p>Every DevOps engineer knows this moment: a service is running fine, but something doesn’t feel right. The code works, the system responds, but deep inside you know… it could be better.</p><p>That’s exactly the situation I found myself in.</p><p>In our company, we had an <strong>internal HTML-to-PDF generation service</strong>. I had deployed it earlier on an <strong>EC2 instance, </strong>and technically, it did its job well.</p><p><strong>Front-end </strong>makes an API call → EC2 processes it → PDF generated.</p><p>Everyone was happy. Or at least, that’s what it looked like. But there was a <strong>hidden issue: </strong>The EC2 instance was running <strong>24/7</strong>. The service wasn’t being used all the time. In fact, it only worked <strong>when someone requested a PDF</strong>. The rest of the time, the instance sat there, silently burning through our budget.</p><p>This was one of those costs that nobody complains about, but every month it quietly eats into the company’s cloud bill.</p><p>As part of the DevOps team, my job is not just to <strong>deploy and maintain services</strong>, but also to <strong>think about sustainability, cost, and scalability.</strong></p><p>When we sat down to review our infrastructure costs, I raised this issue.</p><ul><li>Why should we pay for up-time when the service is not even being used?</li><li>What if we only paid <strong>when PDFs were actually generated</strong>?</li></ul><p>This question set the stage for exploring <strong>AWS Lambda</strong>.</p><p>Lambda’s model was exactly what we needed:</p><ul><li>Pay only for invocations.</li><li>No idle cost.</li><li>Infinite scaling built in.</li></ul><p>It looked like the perfect solution. But I knew it wasn’t enough to just suggest it . I had to <strong>prove it works</strong>.</p><p>Instead of waiting for someone else to test it or forming endless committees, I decided to <strong>build the Lambda version of the service myself</strong>.</p><p>My mindset was: <em>“If I can show the team a working solution that actually saves cost, they’ll not just hear me, they’ll believe me.”</em></p><p>So I started experimenting with R&amp;D.</p><p>Dockerized the PDF service. Looked for a way to handle headless Chromium in Lambda. Discovered <strong>Gotenberg</strong>, a battle-tested open-source PDF engine. Built a <strong>Node.js gateway API</strong> on top of it.</p><p>Designed the container image so it could run smoothly in Lambda.</p><p>It was not always easy. I had problems with dependencies and Lambda containers. But I treated each as an opportunity to learn and push forward<strong>.</strong></p><p>After some trial and error, I had a working Lambda function:</p><ul><li>It generated PDFs on demand.</li><li>It scaled automatically with requests.</li><li>It costs money only when used.</li></ul><p>I tested it thoroughly, documented the flow, and then presented it to my team.</p><p>The best part? Seeing them test it and agree. The solution worked well. We didn’t just save money, we also updated one of our internal services.</p><p><strong>The Takeaways</strong></p><p>This migration taught me two powerful lessons:</p><p>1. <strong>Idle services drain money silently. </strong>Always question whether up-time is really necessary.</p><p>2. <strong>Experimentation drives changes . </strong>My company allows me to explore without rigid boundaries and that freedom turned into a real business win.</p><p>Now our HTML-to-PDF service is:</p><ul><li><strong>Serverless</strong></li><li><strong>Scalable</strong></li><li><strong>Cost-efficient</strong></li></ul><p>Before jumping into Part-02, take a look <a href="https://medium.com/@nahin.cdr/iam-setup-for-ecr-and-lambda-in-aws-ac8d0657a9db"><strong>at this</strong></a>, if you have these permissions/access in AWS. If you don’t have them, ask your admin to give them.</p><p>Continue to <a href="https://medium.com/@nahin.cdr/building-a-pdf-gateway-with-docker-lambda-and-gotenberg-de4e3bf74658"><strong><em>Part : 02</em></strong></a> , where you will learn about the architecture and overview of the service.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30972d277235" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elobyte-software/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-30972d277235">From EC2 to Lambda: How We Deployed a Cost-Effective PDF Service from ECR | Part :</a> was originally published in <a href="https://medium.com/elobyte-software">elobyte-Software</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shifting From EC2 to Lambda: We Deployed a Cost-Effective PDF Service | Part : 02]]></title>
            <link>https://medium.com/elobyte-software/building-a-pdf-gateway-with-docker-lambda-and-gotenberg-de4e3bf74658?source=rss-a0bf9999dd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/de4e3bf74658</guid>
            <category><![CDATA[gotenberg]]></category>
            <category><![CDATA[cost-optimization]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[pdf-converter]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Nazmul Haque Nahin]]></dc:creator>
            <pubDate>Wed, 27 Aug 2025 18:07:23 GMT</pubDate>
            <atom:updated>2025-12-07T05:22:34.252Z</atom:updated>
            <content:encoded><![CDATA[<h4>Architecture and overview of pdf service that we deployed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8rXQqyuuoO0WEEFs691Qw.jpeg" /></figure><p>In <a href="https://medium.com/elobyte-software/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-30972d277235"><strong><em>previous part</em></strong></a> we talked about the scenario we faced , now we will walk you through the journey of creating a PDF generation service, from setting up the back-end with Docker and Lambda to integrating Gotenberg for rendering HTML to PDF. This service is ideal for generating invoices, reports, and any document that can be rendered from HTML. We’ll explore how it works, the architecture behind the service, and the steps taken to deploy it.</p><h4>What will this service render?</h4><p>The primary function of this service is to convert <strong>HTML content</strong> into a <strong>PDF document</strong>. The service uses the <a href="https://gotenberg.dev/"><strong>Gotenberg API</strong></a>,<strong> </strong>which is powered by <strong>Chromium</strong> and <strong>LibreOffice</strong>, and is capable of rendering HTML into high-quality PDFs. This is ideal for use cases such as generating reports, invoices, or print-ready documents directly from HTML templates.</p><h4>What will be our input?</h4><pre><br>{<br>  &quot;html&quot;: &quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello PDF&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;,<br>  &quot;options&quot;: {<br>    &quot;landscape&quot;: false,<br>    &quot;printBackground&quot;: true,<br>    &quot;waitDelay&quot;: &quot;200ms&quot;<br>  }<br>}</pre><p>The service expects the following <strong>input</strong>:</p><p><strong>HTML content</strong> as a string, which will be converted to PDF.</p><ul><li><strong>Options</strong> (optional) as an object, which includes:</li><li><strong>landscape</strong>: Boolean indicating if the document should be in landscape mode.</li><li><strong>printBackground</strong>: Boolean indicating if the background should be printed.</li><li><strong>waitDelay</strong>: Number of milliseconds to wait before starting the PDF rendering process.</li></ul><p>This structured input helps us create customizable PDF outputs that meet different user needs.</p><h4>What will be the desired output?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKfl_Kjn8KRiblywOp9itw.png" /></figure><p>The desired output of this service is a <strong>PDF file</strong> that is generated from the provided HTML input. The service allows users to pass in additional <strong>options</strong> for customizing the output.</p><p>The service will respond with a <strong>PDF document</strong> that can be downloaded or displayed inline, depending on the client’s requirements.</p><h4>Architecture Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWWRwOP1TYGS7docAMW9jg.png" /></figure><p>Here’s how it works:</p><p><strong>Frontend (Client-side):</strong><br>The client sends an HTTP <strong>POST request</strong> to the /generate endpoint, providing HTML and options.</p><p><strong>Backend (Server-side):</strong></p><ul><li><strong>Node.js Express Server</strong>: It handles the request, validates the HTML, and prepares the data.</li><li>It then sends the HTML to the <strong>Gotenberg API</strong> using <strong>Axios</strong>.</li><li>Gotenberg converts the HTML into a <strong>PDF</strong> using <strong>Chromium</strong> and <strong>LibreOffice</strong>.</li></ul><p><strong>Work-Flow Of the Service</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*5w2O3XH3XVCyC3r26HWPYw.png" /></figure><blockquote>In short :</blockquote><ul><li><strong>Client</strong> sends a <strong>POST /generate</strong> request to the <strong>Express server</strong>.</li><li>The <strong>Express server</strong> prepares the <strong>FormData</strong> and sends it to <strong>Gotenberg</strong> via <strong>Axios</strong>.</li><li>The <strong>Gotenberg server</strong> processes the request and returns a <strong>PDF</strong>.</li><li>The <strong>Express server</strong> receives the PDF and sends it back to the <strong>Client</strong>.</li><li>The <strong>Lambda Web Adapter</strong> handles all the communication between <strong>AWS Lambda</strong> and the <strong>Express server</strong>.</li></ul><p>Continue to <a href="https://medium.com/@nahin.cdr/from-ec2-to-lambda-how-we-deployed-a-cost-effective-pdf-service-from-ecr-part-03-412f957d7be6"><em>Part: 03</em></a>, where we will discuss the gateway code with explanations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de4e3bf74658" width="1" height="1" alt=""><hr><p><a href="https://medium.com/elobyte-software/building-a-pdf-gateway-with-docker-lambda-and-gotenberg-de4e3bf74658">Shifting From EC2 to Lambda: We Deployed a Cost-Effective PDF Service | Part : 02</a> was originally published in <a href="https://medium.com/elobyte-software">elobyte-Software</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IAM Setup for ECR and Lambda in AWS]]></title>
            <link>https://medium.com/@nahin.cdr/iam-setup-for-ecr-and-lambda-in-aws-ac8d0657a9db?source=rss-a0bf9999dd08------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac8d0657a9db</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[aws-ecr]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Nazmul Haque Nahin]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 11:37:27 GMT</pubDate>
            <atom:updated>2025-09-01T15:42:07.553Z</atom:updated>
            <content:encoded><![CDATA[<h4>User &amp; Role Setup: The Foundation for Deployment</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sh7fNo1oE5u5HHjMGE5hHQ.png" /></figure><h4>Setting up Access (the simple way with AWS Console)</h4><p>Before pushing images to <strong>ECR</strong> or deploying them in <strong>Lambda</strong>, the user (you or your teammate) needs the right permissions. Here’s the easiest way to set it up using the <strong>AWS Console only</strong>.</p><h4>1. Create a User (or use an existing one)</h4><ul><li>Go to <strong>IAM</strong> in AWS Console.</li><li>In the left menu, click <strong>Users</strong> → <strong>Add users</strong>.</li><li>Give the user a name (e.g., devops-user).</li><li>Select <strong>Attach policies directly</strong>.</li></ul><h4>2. Attach Required Permissions</h4><p>Tick these managed policies:</p><ul><li><strong>AmazonEC2ContainerRegistryFullAccess</strong> → lets you push and pull images from ECR.</li><li><strong>AWSLambda_FullAccess</strong> → lets you create and update Lambda functions.</li><li><strong>IAMFullAccess</strong> (or at least PassRole rights) → needed so you can attach an execution role to Lambda.</li></ul><p>If you want to be stricter: you can create a dedicated Lambda execution role separately, but for a simple setup, these three policies will let your user do everything needed.</p><p>Click <strong>Next</strong> → <strong>Create user</strong>.</p><h4><strong>3. Create a Role for Lambda to Run</strong></h4><p>The Lambda itself also needs permission to write logs.</p><ol><li>Go to <strong>IAM → Roles</strong> → <strong>Create role</strong>.</li><li>Select <strong>Trusted entity: AWS Service → Lambda</strong>.</li><li>Attach the policy <strong>AWSLambdaBasicExecutionRole</strong>.</li></ol><ul><li>This allows Lambda to send logs to CloudWatch.</li><li>Name the role something like pdf-lambda-exec</li><li>Create the role.</li></ul><h4>4. Summary of Who Has What</h4><ul><li><strong>Your IAM User</strong> → Can:</li><li>Push images to ECR</li><li>Create/Update Lambda functions</li><li>Attach roles to Lambda</li><li><strong>Lambda Execution Role</strong> → Used <strong>by the Lambda at runtime</strong> to:</li><li>Write logs to CloudWatch</li></ul><h4><strong>That’s it. With these steps, your user has everything needed to:</strong></h4><ul><li>Build &amp; push images into <strong>ECR</strong></li><li>Deploy them into <strong>Lambda</strong></li><li>Attach the Lambda execution role for logging</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac8d0657a9db" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>