How to 301 redirect from url with post id to permalink with post name (slug)?

yes, it is possible. add a template_redirect hook handler:

add_filter('template_redirect', 'redirect_post_to_canonical_url');

function redirect_post_to_canonical_url(): void
{
    if (!is_single()) {
        // do not redirect nothing else except posts
        return;
    }


    $canonicalLocation = get_permalink();
    $requestUri = $_SERVER['REQUEST_URI'];
    $currentLocation = home_url("https://wordpress.stackexchange.com/") . substr($requestUri, 1);
    if ($currentLocation === $canonicalLocation) {
        // prevent from infinite redirect loop
        return;
    }

    wp_redirect($canonicalLocation, 301);
}