<?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 Mahmood Al Rayhan on Medium]]></title>
        <description><![CDATA[Stories by Mahmood Al Rayhan on Medium]]></description>
        <link>https://medium.com/@rayhan-craftsmen?source=rss-a0cffae88480------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZHNK7WO6UK-aVlMz-OUtTQ.jpeg</url>
            <title>Stories by Mahmood Al Rayhan on Medium</title>
            <link>https://medium.com/@rayhan-craftsmen?source=rss-a0cffae88480------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:38:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rayhan-craftsmen/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[AWS Lambda Function in GoLang]]></title>
            <link>https://medium.com/craftsmenltd/aws-lambda-function-in-golang-eb0a3fa5f1b9?source=rss-a0cffae88480------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb0a3fa5f1b9</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[function-as-a-service]]></category>
            <dc:creator><![CDATA[Mahmood Al Rayhan]]></dc:creator>
            <pubDate>Wed, 28 Oct 2020 19:39:40 GMT</pubDate>
            <atom:updated>2020-10-29T03:47:48.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4kD68gYM1J1Fu-J7qvSSA.png" /><figcaption>Source: <a href="https://blog.travelex.io/blazing-fast-microservice-with-go-and-lambda-d30d95290f28">https://blog.travelex.io/blazing-fast-microservice-with-go-and-lambda-d30d95290f28</a></figcaption></figure><p>AWS <strong>Lambda</strong> is a well known and great cloud <strong>Function as a Service</strong> (FaaS). And Google’s <strong>GoLang</strong> is a statically typed, compiled programming language. It is widely popular for it is being super <strong>fast</strong> and it’s <strong>built-in concurrency</strong>.</p><p>In this blog post, we will discuss how we can use <strong>GoLang in the AWS Lambda function</strong>. In this demonstration, I’m using <strong>Go1.15</strong>. Following things are assumed:</p><ul><li>You know how to setup GoLang for development in Unix systems</li><li>You are familiar with AWS Lambda</li></ul><p>As <strong>Go</strong> is a compiled language, we cannot use the Lambda Function’s editor to edit the GoLang source code which we can do it in the case of scripting languages like Python, NodeJS, etc. In the case of Go, we will build the <strong>main</strong> function’s (the main function starts the lambda handler) file (cmd/main.go) which will create a <strong>compiled executable </strong>that is to be deployed to AWS Lambda. Let’s see step by step how a GoLang function can be created and deployed to AWS Lambda. We will use the following <strong>project structure</strong> in this demo, but you can use any structure at your convenience.</p><pre>lambda-function-in-golang/<br>    cmd/<br>        main.go<br>        main_test.go<br>        ...<br>    deploy/<br>        ...<br>    scripts/<br>        ...<br>    go.mod<br>    go.sum</pre><h3>Lambda Handler</h3><p>Let’s look at how <strong>cmd/main.go</strong> look like:</p><pre>package main<br><br><br>import (<br>	&quot;fmt&quot;<br><br>	&quot;github.com/aws/aws-lambda-go/lambda&quot;<br>)<br><br><br>type LambdaEvent struct {<br>	Name string `json:&quot;name&quot;`<br>	Age int `json:&quot;age&quot;`<br>}<br><br><br>type LambdaResponse struct {<br>	Message string `json:&quot;message&quot;`<br>}<br><br><br>func LambdaHandler(event LambdaEvent) (LambdaResponse, error) {<br>	return LambdaResponse {<br>		Message: fmt.Sprintf(&quot;%s is %d years old.&quot;, event.Name, event.Age),<br>	}, nil<br>}<br><br><br>func main ()  {<br>	lambda.Start(LambdaHandler)<br>}</pre><p>github.com/aws/aws-lambda-go/lambda is the <strong>AWS SDK for GoLang</strong>. LambdaEvent is used to store the event and this is a custom event. Instead of using this custom event, different AWS service specific events can be used. For AWS service specific events, github.com/aws/aws-lambda-go/events this package can be used. LambdaResponse is used to store the response to be returned.</p><h4>Some rules regarding the Lambda Handler are as follows:</h4><ul><li>The Handler must be a function.</li><li>The handler may take 0 to 2 arguments.</li><li>If there is only one argument, it can be the context. Context, or an event from github.com/aws/aws-lambda-go/events this package or any custom event.</li><li>If there are 2 arguments used, the first one must be context.Context.</li><li>The handler may return 0 to 2 value.</li><li>If there is only one value, it must implement error.</li><li>If there are 2 return values, the second value must implement error.</li></ul><h4>Valid Lambda Handler function signature:</h4><ul><li>func ()</li><li>func () error</li><li>func () (TOut, error)</li><li>func (TIn), error</li><li>func (context.Context) error</li><li><strong>func (TIn) (TOut, error)</strong></li><li>func (context.Context) (TOut, error)</li><li>func (context.Context, TIn) error</li><li>func (context.Context, TIn) (TOut, error)</li></ul><p>Here, TIn and TOut represent the <strong>event</strong> and <strong>response</strong> respectively.</p><p><strong>NOTE:</strong> Global variables that are independent of your Lambda function’s handler code can be declared and modified. The handler may declare an init a function that is executed when your handler is loaded.</p><h3>Create Compiled Executable And Prepare It For AWS Lambda</h3><ul><li>To build the executable, run the following command in the project root directory.</li></ul><pre>GOOS=linux go build cmd/main.go</pre><p>GOOS=linux will ensure that the compiled executable is <strong>Linux environment compatible</strong>, even if it is built/compiled in a non-Linux environment. This command will create a compiled <strong>executable</strong> named <strong>main</strong> in the project root directory.</p><ul><li>Zip the compiled executable <strong>main</strong>.</li></ul><pre>zip function.zip main</pre><h3>Create The Function</h3><ul><li>Create the lambda function using the following command.</li></ul><pre>aws lambda --profile craftsmen --region us-east-2 create-function --function-name lambda-go --runtime go1.x --zip-file fileb://function.zip --handler main --role arn:aws:iam::{account-id}:role/service-role/basic_lambda_execution</pre><p>Replace {account-id} in the above command with your actual account id. You can use your own role ARN too.</p><h3>Test The Function</h3><ul><li>Configure test event as follows</li></ul><pre>{<br>    &quot;name&quot;: &quot;Rayhan&quot;,<br>    &quot;age&quot;: 25<br>}</pre><ul><li>Test the function. This will give <strong>{ “message”: “Rayhan is 25 years old.” }</strong> as a response.</li></ul><h3>Lambda Layers</h3><p>You may wonder that external package(s) (AWS GoLang SDK) has been used, but there are no <strong>Lambda Layers</strong> for the external packages. Actually, when the application is <strong>compiled</strong>, the <strong>compiled executable includes all the external packages</strong> used. To get benefit from the AWS Lambda Layer, <strong>GoLang Plugins</strong> can be used. Golang Plugins is the feature released in the Go1.8. It allows you to dynamically load shared libraries (.so files). It gives you an opportunity to export some of your code to a separate library or use the plugin prepared and compiled by someone else.</p><p><strong>The full project source code along with the Terraform configuration can be found </strong><a href="https://github.com/MhmdRyhn/lambda-function-in-golang"><strong>HERE</strong></a><strong>.</strong></p><h4>Stay in Peace and Keep Coding !!!</h4><h3>References</h3><ul><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/lambda-golang.html">Building Lambda functions with Go</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/golang-handler.html">AWS Lambda function handler in Go</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/golang-package.html">AWS Lambda deployment package in Go</a></li><li><a href="https://medium.com/nordcloud-engineering/how-to-build-pluggable-golang-application-and-benefit-from-aws-lambda-layers-154c8117df9b">How to build pluggable Golang application and benefit from AWS Lambda Layers.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb0a3fa5f1b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/craftsmenltd/aws-lambda-function-in-golang-eb0a3fa5f1b9">AWS Lambda Function in GoLang</a> was originally published in <a href="https://medium.com/craftsmenltd">Craftsmen — Software Maestros</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQLAlchemy and The Unit of Work Pattern]]></title>
            <link>https://medium.com/craftsmenltd/sqlalchemy-and-the-unit-of-work-pattern-dfa91a098023?source=rss-a0cffae88480------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfa91a098023</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[unitofwork]]></category>
            <dc:creator><![CDATA[Mahmood Al Rayhan]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 10:17:31 GMT</pubDate>
            <atom:updated>2020-06-03T10:17:31.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tt4C5PVYSXgRnOmNACG-vw.jpeg" /><figcaption>Image Source: <a href="https://i2.wp.com/regionweek.com/wp-content/uploads/2018/12/14th-taking-resikssUnity-is-strength_shark.jpg?ssl=1">https://i2.wp.com/regionweek.com/wp-content/uploads/2018/12/14th-taking-resikssUnity-is-strength_shark.jpg?ssl=1</a></figcaption></figure><p>SQLAlchemy is a very powerful and easy to use ORM written in Python. It really helps to develop applications faster. This blog post is about how we can use Unit of Work pattern when using SQLAlchemy ORM (an ORM written in Python for Relational Databases).</p><p>This blog post assumes that you are already familiar with SQLAlchemy, know how to setup and connect to database and know how to play with basic operations using SQLAlchemy.</p><h3>Traditional way to do a business transaction</h3><p>When a business transaction involves several database operations, traditionally what you do is you perform each operation separately inside a transaction block. This can lead to lots of very small database calls, which ends up being very slow. Moreover it requires you to have a transaction open for the whole interaction, which is impractical if a business transaction needs multiple requests to be completed.</p><p>This is a problem in traditional way of performing a business transaction. The Unit of Work design pattern helps to solve these kind of situations.</p><h3>What is Unit of Work Pattern and How It Works</h3><p>A Unit of work is a design pattern which is basically used in performing database transactions.</p><p>“A Unit of Work is used to maintain a list of objects affected by a business transaction and to coordinate the writing out of these changes.” — <strong>Martin Fowler</strong></p><p>A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you’re done, it figures out everything that needs to be done to alter the database as a result of your work [2]. Unit of Work design pattern does two important things [3]:</p><p>(1) It maintains lists of business objects in-memory which have been changed (inserted, updated, or deleted) during a transaction.</p><p>(2) It then sends these in-memory updates as one big unit of work (transaction) to the database.</p><p><strong>Still confusing?</strong> Lets illustrate this with an example.</p><h3>The Problem</h3><p>Suppose, you have an e-commerce application, where your users can order products by using your application. When a user creates an order, this order can contain several items of different quantity. You need to save the order along with the items and the quantity into the database.</p><p>Suppose the Database models are as follows:</p><p>Note: The models bellow are PostgreSQL compatible only. You can use any other Relational Databases supported by SQLAlchemy and change the models accordingly.</p><p><strong>models.py: </strong>you can check the bellow code <a href="https://github.com/MhmdRyhn/blogs/blob/master/unit_of_work/models.py">here</a> too.</p><pre>class Order(Base):<br>    __tablename__ = &#39;order&#39;<br>    <br>    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)<br>    # Foreign key referencing User model. User model is not shown here for simplicity<br>    user_id = Column(UUID(as_uuid=True), ForeignKey(&quot;user.id&quot;, ondelete=&#39;RESTRICT&#39;), nullable=False)<br>    last_updated_at = Column(DateTime, nullable=False, onupdate=func.utcnow, default=datetime.datetime.utcnow)<br>    # Related items of an order<br>    order_items = relationship(&#39;OrderItem&#39;, backref=&#39;order&#39;, uselist=True)<br><br><br>class OrderItem(Base):<br>    __tablename__ = &#39;order_item&#39;<br>    <br>    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)<br>    order_id = Column(UUID(as_uuid=True), ForeignKey(&quot;order.id&quot;, ondelete=&#39;RESTRICT&#39;), nullable=False)<br>    # Foreign key referencing Product model. Product model is not shown here for simplicity<br>    product_id = Column(UUID(as_uuid=True), ForeignKey(&quot;product.id&quot;, ondelete=&#39;RESTRICT&#39;), nullable=False)<br>    quantity = Column(Integer, nullable=False)<br>    last_updated_at = Column(DateTime, nullable=False, onupdate=func.utcnow, default=datetime.datetime.utcnow)</pre><p>And, the incoming data having the order details is of the following structure. You can check the following code <a href="https://github.com/MhmdRyhn/blogs/blob/master/unit_of_work/operations.py#L4">here</a> too.</p><pre>order_data = {<br>    &#39;user_id&#39;: &#39;d1e20a44-b5cf-4d34-b9cd-4ee3d6c23f59&#39;,<br>    &#39;order_items&#39;: [<br>        {<br>            &#39;product_id&#39;: &#39;179d74ab-d2cd-4eef-a6c0-526d5c1606cc&#39;,<br>            &#39;quantity&#39;: 4<br>        },<br>        {<br>            &#39;product_id&#39;: &#39;3dc761d2-a3db-4672-a1a9-e002635afe70&#39;,<br>            &#39;quantity&#39;: 5<br>        }<br>    ]<br>}</pre><h3>Solution 1: using the traditional way</h3><p><strong>operations.py:</strong> you can check the following code <a href="https://github.com/MhmdRyhn/blogs/blob/master/unit_of_work/operations.py#L19">here</a> too.</p><pre>def create_order_traditional(data):<br>    user_id = data.pop(&#39;user_id&#39;)<br>    order = Order(user_id=user_id)<br>    session.add(order)<br>    session.commit()<br>    for item in data[&#39;order_items&#39;]:<br>        order_item = OrderItem(order_id=order.id, product_id=item[&#39;product_id&#39;], quantity=item[&#39;quantity&#39;])<br>        session.add(order_item)<br>        session.commit()<br>    session.close()</pre><p>In the above order creation operation, session.commit() will be called 3 times to complete the transaction, i.e., it&#39;s calling database 3 times. So, what if the payload you are saving is much bigger? This will use more number of database call.</p><p>Let’s try to get the same effect in database using <strong>Unit of Work</strong>.</p><h3>Solution 2: using Unit of Work Pattern</h3><p><strong>operations.py:</strong> you can check the following code <a href="https://github.com/MhmdRyhn/blogs/blob/master/unit_of_work/operations.py#L30">here</a> too.</p><pre>def create_order_unit_of_work(data):<br>    user_id = data.pop(&#39;user_id&#39;)<br>    order_item_object_list = []<br>    for item in data[&#39;order_items&#39;]:<br>        order_item = OrderItem(product_id=item[&#39;product_id&#39;], quantity=item[&#39;quantity&#39;])<br>        order_item_object_list.append(order_item)<br>    order = Order(user_id=user_id, order_items=order_item_object_list)<br>    session.add(order)<br>    session.commit()<br>    session.close()</pre><p>Here, notice that session.commit() is called only once. All the other operations (in this case, the insert) were done in-memory and then sent to database as a big unit of work. SQLAlchemy will handle the rest of the thing using Unit of Work pattern. This way is much more efficient than the traditional one. It doesn&#39;t require you to save each object separately, thus helps to prevent the transaction being slow. You just need to manipulate the objects in-memory and then send the whole unit of objects at a time, SQLAlchemy will handle the rest of the thing on your behalf.</p><p>This pattern can be applied in the case of update and delete operations too. In those cases, you&#39;ll update and/or delete multiple objects in-memory and finally apply session.commit() to reflect the changes in database.</p><p><strong>Happy Coding !!!</strong></p><h3>References</h3><p>[1] <a href="https://docs.huihoo.com/python/sqlalchemy-0.3/unitofwork.html">SQLAlchemy: Session / Unit of Work</a></p><p>[2] <a href="https://martinfowler.com/eaaCatalog/unitOfWork.html">Unit of Work by Martin Fowler</a></p><p>[3] <a href="https://www.codeproject.com/Articles/581487/Unit-of-Work-Design-Pattern">Unit of Work Design Pattern</a></p><p>[4] <a href="https://auth0.com/blog/sqlalchemy-orm-tutorial-for-python-developers">SQLAlchemy ORM Tutorial for Python Developer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfa91a098023" width="1" height="1" alt=""><hr><p><a href="https://medium.com/craftsmenltd/sqlalchemy-and-the-unit-of-work-pattern-dfa91a098023">SQLAlchemy and The Unit of Work Pattern</a> was originally published in <a href="https://medium.com/craftsmenltd">Craftsmen — Software Maestros</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>