Software

SSE vs WebSockets

SSE vs WebSockets – Exploring for Efficient Communication

1024 1024 Ahmet Onur

In the realm of real-time communication on the web, developers often find themselves at a crossroads when selecting the most suitable protocol. Should they opt for Server-Sent Events (SSE) or WebSockets (SSE vs Websockets)? This decision hinges on various factors, including the nature of user interaction and the specific requirements of the application.

Understanding SSE vs WebSockets

SSE and WebSockets represent two distinct approaches to facilitating communication between clients and servers. SSE provides a straightforward mechanism for server-to-client messaging, ideal for scenarios where one-way communication suffices. On the other hand, WebSockets offer bidirectional communication capabilities, making them suitable for applications requiring real-time interaction between clients and servers.

Differentiating Factors

When deliberating between SSE and WebSockets, several crucial factors come into play:

  1. Nature of Communication: SSE excels in scenarios where the server primarily sends data to clients, such as broadcasting telemetry or disseminating live updates. In contrast, WebSockets are more appropriate for applications requiring frequent exchanges of data between clients and servers, such as chat platforms.
  2. Protocol Overhead: Both SSE and WebSockets entail minimal protocol overhead once the connection is established. However, SSE eliminates the need for a handshake, resulting in a more streamlined initial connection compared to WebSockets.
  3. Implementation Complexity: SSE boasts simplicity in its architecture, making it easier to implement for scenarios involving one-way communication. Conversely, WebSockets offer more flexibility but may require additional effort to handle bidirectional messaging efficiently.

Making the Right Choice

Choosing between SSE and WebSockets boils down to understanding your application’s requirements and considering the following:

  1. User Interaction: Evaluate the frequency and nature of user interactions within your application. If the majority of communication involves server-to-client updates with minimal client-side input, SSE might be the optimal choice.
  2. Implementation Considerations: Assess the complexity of implementing SSE versus WebSockets in your specific use case. While SSE offers simplicity, WebSockets provide versatility but may require more intricate setup for bidirectional communication.
  3. Scalability and Performance: Consider the scalability implications of your chosen protocol, especially when dealing with a large user base. Factors such as message aggregation, server load balancing, and infrastructure choices play a crucial role in ensuring optimal performance.

Conclusion

In conclusion, the decision between SSE vs WebSockets hinges on various factors, including the nature of communication, implementation complexity, and performance considerations. While SSE excels in simplicity and efficiency for one-way communication scenarios, WebSockets offer versatility for applications requiring bidirectional interaction. By carefully evaluating your application’s requirements and considering these factors, you can make an informed decision to enhance the real-time communication experience for your users.

In the dynamic landscape of web development, staying abreast of the latest trends and technologies is paramount. Whether you opt for SSE vs WebSockets, prioritizing seamless communication and user experience remains paramount in driving the success of your web applications.

Resources about SSE vs Websockets

How to use server-sent events? Here you can learn

Time to explore async vs defer in Javascript. Take a look at:

async vs defer javascript

Async vs Defer JavaScript – Exploring the Differences

1024 1024 Ahmet Onur

JavaScript is a fundamental building block for today’s web applications. But have you ever wondered how browsers handle HTML and JavaScript files? If you haven’t tried crazy things probably you didn’t use async or defer while loading JavaScript files. Let’s take a closer look what is difference between async vs defer javascript.

How Browsers Read HTML: Understanding the Contrast between Async and Defer JavaScript

When you navigate to a website, your browser starts by parsing the index.html file from top to bottom. If it encounters a <script> tag, it temporarily pauses HTML parsing to execute the JavaScript code. Once the JavaScript execution is complete, it resumes parsing the HTML.

This is the default behavior when including a JavaScript file:

<script src="app.js"></script>

This method suits websites that rely on multiple JavaScript files, some of which may depend on others.

Quick JavaScript: Async Method

The ‘async’ attribute allows JavaScript files to load asynchronously. This means that while the browser parses the HTML, it simultaneously fetches JavaScript files marked with ‘async’.

The JavaScript code within these files will execute as soon as they are downloaded, irrespective of whether the HTML parsing is complete. This can significantly accelerate page loading times.

Here’s how you can utilize the ‘async’ attribute:

<script src="app.js" async></script>

In ‘async’ mode, JavaScript files are non-blocking, ensuring that your page remains responsive. This feature is particularly useful for integrating third-party scripts like ads or analytics tools, which do not rely on your scripts.

Waited JavaScript: Defer Feature

Similar to ‘async’, the ‘defer’ attribute delays the execution of JavaScript until the HTML parsing is complete. However, it maintains the order of script import, ensuring that scripts are executed in the sequence they appear in the HTML file.

In ‘defer’ mode, the browser fetches the script while parsing the HTML but postpones execution until the HTML parsing is finished.

Here’s how you can use the ‘defer’ attribute:

<script src="app.js" defer></script>

While ‘defer’ mode may slightly slow down page rendering due to sequential execution, it ensures proper script dependency resolution.

Conclusion

In summary, there are two distinct strategies for loading JavaScript files: async vs defer javascript. The choice between them depends on your specific requirements.

For scripts that do not rely on others, such as Google Analytics, ‘async’ loading can significantly enhance website performance. On the other hand, if you need to ensure script dependency resolution, ‘defer’ loading may be more suitable.

Understanding these loading strategies empowers developers to optimize their web applications for improved performance and user experience.

Have you ever seen .well-known path, don’t you know what is meaning of it? Lets look together

Teknasyon PHPKonf 2023

Teknasyon PHPKonf 2023 Summary

1024 1024 Ahmet Onur

I just attend to Teknasyon PHPKonf 2023 that took place in Istanbul Kultur University. It was really absorbing. Speakers have provided valuable information, insights, or experiences related to PHP programming or technology in general. You can be informed about some of talks in this post.

Real-world Async Cases with Fibers – Mert Şimşek

This is about the fibers feature of PHP to add ASYNC behaviour. Fibers feature is like Promise from JavaScript. They can start, stop, resume and cancel if you wish. You can prioritise jobs by using fibers. It expects the callback function to execute. You can check fibers documentation out here.

Event-Driven State Machines – Yunus Emre Deligöz

Every programmer definitely uses conditions to manage the state of class. For example, if you want to program traffic lights in code, you have to keep traffic lights’ state status and then manage behaviours and its effects. Firstly, you can do this with if/else conditions but it makes things hard to write tests and means that you have to write tests for every conditions and condition combinations.

State machines is an approach like OOP to program these stateful mechanisms by keeping the codebase clean and durable. This is called finite-state machines.

Assume that we have http fetch service. This has states (not started, fetching, success, error) and behaviours (fetch, success, refresh, error). When we need to send http request, this machine has to change its state to “fetching” and while it is happening, it shouldn’t accept new http fetch requests. And then according to result of request, it should be changed to success or error states. Thanks to state machines, we can implement behaviours and make state changes without using conditions.

Teknasyon PHPKonf 2023 state machines

NOTE: If you want to use packages for that, there are config, behaviour, definition and actor elements.

NOTE: Guards are responsible for controlling whether behaviour is possible to do. If it isn’t, the guard rejects the action.

RESOURCE: Speaker has also shared slide and resources here.

Dealing with High Traffic: Experiences in Redis and PHP – Ali Özkan

–latency command

Latency is great command to check maximum delay between issuing command and the time the reply to the command.

When Redis is loaded high requests, to handle it:

  • AOF should be turned off
  • RAM should be prevented to reach maximum memory to keep redis up, so we should set eviction policy to “noeviction” because other eviction policy values might not keep up with redis memory. For example, if we set it to “volatile-ttl”, redis might not handle sorting of keys and deleting them in order while new keys are coming to Redis, so the solution is writing own redis key manager to guard incoming new keys if redis can’t put them.
  • If we scale the redis up in order to keep new keys inside, it might not be useful when we reach scaling threshold. We can open new places for new keys while extending RAM; however, CPU increment doesn’t help the redis to put, read or update keys because redis is single-thread. Every requests are handled in sync and after threshold, the redis can’t handle it.
  • The solution is using redis cluster feature. The cluster feature creates new virtual instances and manages keeping keys on them. For example, if y0u want to a key that called “AHMET” on Redis, it checks whether the key is in cluster 1 or not. Then if it is not, it looks another clusters automatically to find.

NOTE: After adding new clusters to Redis, we should allow it to know them. At the beginning, they won’t receive new keys and we have to move slots to new clusters in order to active them. You can check clusters with cluster info command. In short, cluster_size and cluster_known_nodes properties should show same counts. If they are not same, it means that you have not activated clusters.

Introduction to Mutation Testing – Can Vural

Code coverage checks don’t show code and test quality. It is only show that which parts of your code tested. Anyway, it doesn’t let us know that it doesn’t cause any problem when it is published.

Mutation tests help us to measure quality of our tests. Basically it changes code and generate new mutations, then test scenarios, so we can be sure about our code in order to deploy to production. Disadvantage of the mutation test is slowness. Compared to unit tests it lasts long and if possible we should test our code partially.

Transforming the Past: Refactoring Adventure of a 5-Year Project – Görkem Duymaz

We should create regression tests for every refactoring change in order to check whether new code and old code have same functionality or not.

And also some points that we need to be careful while working on refactoring:

  • Should be prepared to refactoring process
  • Should avoid to do thing that comes to mind first. It should be planned and refined well.
  • Refactoring is not one-time job. It is actually mindset and should be planned as a process and in time this mindset should be implemented.
  • Dependency is a dangerous point while making refactor.
  • Deployment of refactored code should be made partially and avoid to wait until completing all of code.
  • Performance tests should be done to not have inefficient code
  • Code analysing should be prioritised
  • If you continue adding new feature while working on refactoring, you should follow same mindset to keep debt less.
  • Documentation is so important and we should keep it updated.

Beyond Controllers in Laravel Projects: Finding the Right Place for Logic – Mücahit Cücen

In this talk, presenter generally told that laravel documentation, so i will list some of points.

Traits

Traits are like abstract classes. Difference between them is trait classes are not specific purposes, so they can be used in different modules and domains but abstract classes are domain based. Anyway, you can inject them to your parent class and use their behaviour in it.

Repository classes pattern in Laravel

You should avoid from using this pattern in Laravel. Implementation of this pattern is actually service architecture but this causes performance issues and complicated codebase.

Thank you for reading my post about Teknasyon PHPKonf 2023 summary. If you want to make contribution to this post, don’t hesitate to reach me.

moving just single commit from branch to another branch.

Moving just single commit from branch to another branch

1024 1024 Ahmet Onur

Cherry-pick is life-saving git tool for moving just single commit from branch to another branch. To illustrate, you have to fix an issue quickly and you accidentally sent commit to develop branch and you realised that there are another commit from another developers, so you can’t open merge request from develop to master and can’t merge it immediately.

If you are sure there is no obstacle to move just fix commit to master, you can use cherry-pick to move the commit properly.

How to do “cherry-pick”?

Find commit hash

Go your commit history in git UI and get commit hash.

Switch to desired branch

Be sure you are on the branch that you want to move commit to it

git switch master

Let’s use cherry-pick

 git cherry-pick <commit-hash>

Push commit to branch

git push origin master

Congrats! 🎉 Your commit is also in master branch and great for you to deliver fix.

You can look up git cherry-pick documentation in detail here:

https://git-scm.com/docs/git-cherry-pick

Have you ever seen “.well-known” folder before? I think you already did. Let’s look together what it is

How to build PHP Image from Scratch

How to build PHP Image from Scratch

1024 1024 Ahmet Onur

Today, we will build PHP Image from Scratch in order to deploy base PHP applications easily. Please keep in mind, this is development purposes for beginners. We will publish new article for production purposes.

Let’s get started.

Preparing Dockerfile for base PHP applications

Firstly, create Dockerfile to list configuration. At the beginning of the page, we start by adding this line.

FROM php

This enables us to install php.

Secondly, we add a new line to use files.

COPY . .

So that you can access every files in main root. However, if you wish use to only specific files, you can specify them manually like:

COPY ./index.php ./

Thanks to this, you can just move specific files and they are available to use.

In the next step, we expose desired port to run php application.

EXPOSE 3000

At the end of the file, we can run our app by executing following command line.

CMD ["php", "-S", "0.0.0.0:3000"]

To make life easier for you, you can get the file entirely.

FROM php
COPY . .
EXPOSE 3000
CMD ["php", "-S", "0.0.0.0:3000"]

Installing docker image

Executing this command line, you can get php image.

docker build . -t w3cloudhub/php

Running docker image

docker run --name=php -p=3000:3000 w3cloudhub/php

Congratulations! 🥳 If you see following line in the CMD, your dockerfile and image are ready to use.

PHP 8.2.0 Development Server (http://0.0.0.0:3000) started

Thank you for reading. Please leave a comment about your feelings and any issues.

what is meaning well-known path

What is meaning of .well-known path?

1024 1024 Ahmet Onur

If you built a website, you have already seen .well-known path but I claim that you do not know what it is and why it is there. 🙂

When you setup a website on cpanel or pleks and then access to file system of the website, there is a folder or path that is called .well-known.

We are familiar with the name but most of us don’t care what it is actually.

What is .well-known path?

.well-known path or folder name is about giving reference to your website or app from other services. To illustrate, when you visit password manager inside chrome browser for a specific website and click to change password, it redirects you to website’s .well-known/change-password page. If the website that you want to change your password is already handled, you will be automatically redirected to website’s password change page. If not, as a user you will be disappointed.

How should we handle .well-know/change-password route?

There are actually 2 ways to handle this.

Redirecting the path to desired page

Assume that we have auth/forget-password page that enables user to change their password on our app. We just need to set our server to redirect requests from .well-known/change-password path to auth/forget-password page.

Redirecting via giving a response with 302, 303 or 307 status code can be accepted.

302 Status Code – Found

303 Status Code – See Other

307 Status Code – Temporary Redirect

Serving via HTML

You can simply add this meta tag in html file that is located .well-known/change-password path, the route will redirect users to desired page.

<meta http-equiv="refresh" content="0;url=https://example.com/auth/forget-password">

The .well-known/change-password practice is accepted by nearly entire web world. You can improve user experience on your web apps so that real users can access password change page properly from redirecting password managers or browsers to your app.

How do we test .well-known/change password function?

Simply copy and paste this chrome://settings/passwords/ URL in your chrome browser. And then click to change password button in right-hand side of any saved password. The button will redirect user to website’s password change page. (of course if it is already setup 🙂 )

well-known path - chrome password page

Furthermore, there are lots of .well-known folder practices and you can check them out here as we add step by step.

We list important but not known technical updates here in our software world updates page. You can follow new improvements and updates in software world.

request/response cycle of django

Request/Response Cycle of Django – Basic

1024 1024 Ahmet Onur

Django is a popular framework that is used by many high level tech companies for back-end development. Django has lots of handy structure to handle web applications. One of them is request/response cycle of django that we will cover today. As a developer understanding the request/response cycle gives you more efficient control on your Django app, actually on your all web apps.

Request and response are fundamentals of basic web applications. They are actually two points that have cycle between them. While request is starting-point, response is ending-point of process. When a user who wants to use your app, our app uses this cycle in order to give response to user. There are structures, parts and middlewares that in the cycle handle your request object, modify request data, coupling with business logic and creates new response object. Response object also go through cycle and raises across the user.

Request/Response Cycle of Django

Client raises request

Request arises when user wants to use app. We call it as “client“. Client sends request to our app. This request might include some data, parameters and logical information.

Web server greets request

A client sent request to our app and web server that runs our app greets request. It receives request and sends to connector that might be called WSGI between framework and web server.

WSGI handles request

Web servers do not know frameworks and frameworks do not web server too, so we need to have connector between them. WSGI handles request and converts to format that framework is able to understand. Request with all its extra data and information lands to framework.

Request Middlewares

Middlewares are important of the cycle because you can interfere a request before your specific business logic parts. All request goes through middlewares and meanwhile you can mutate request by your requests. Authentication control, formatting are some examples of middlewares.

URL Resolution

Requests might come to our app but we need to know they are related which business logic, so our app has different urls (paths and routers). Each url has own business logic function and each url is separate between. To illustrate, to authentication user with your app, your front-end app requests your app’s https://api.ahmetonursolmaz.com.tr/auth point and our app can understand request’s purpose and send it to specific business logic part of app. After middlewares mutated our request and now request should go to where it belongs. 🤣 URL resolution enables us to redirect request to views.

Views

Views are business logic part of your app. You can do everything that you want related with your logic. You can connect your databases, insert data there or retrieve data from there. In short, you can do everything for your specific purpose. After your transaction on request, in this part we need to create response object that we can use. Request object dead and now we have response object. This response object has two different type. One of them is success and another one is exception (fail). Success response goes to global middlewares directly but exception responses go to its specific middlewares. After exception goes through middlewares that are for fail status, also it goes to global middlewares.

Response Middlewares

Our view has prepared response object but we need to make sure response is ready to raise to user. Like all requests goes through request middlewares, all responses also go through response middlewares and you can mutate all responses globally there. We can return standart format to user.

Again, WSGI

Our framework handled request and created new response object, After all, our framework’s job is over and time to convert it to format that web server understand. Like start-point, at the moment WSGI converts our response object to web server’s format.

Web server returns response

Our response is ready for user 🥳 and web server returns it to user with HTTP. User can see request’s detail and response data.

We have covered all request/response cycle of django framework in basic level without using advanced terms. That one is fully proper for starting level and we are going to go through this topic in advanced level. You can subscribe to our articles to follow series. Thanks for all you reading and good to develop something everyone!